SQL Python Connectivity
SQL Python Connectivity
def show_name_asc():
mycur.execute("SELECT * FROM EMP ORDER BY Name")
recs = mycur.fetchall()
ctr = mycur.rowcount
print("Total records -",ctr)
for r in recs:
print(r[0],r[1],r[2],r[3],r[4],sep="\t")
Employee Details Manipulation Using MySQL-Python
def show_name_desc(): #UDF to display records in descending order of name
mycur.execute("SELECT * FROM EMP ORDER BY Name DESC")
recs = mycur.fetchall()
ctr = mycur.rowcount
print("Total records - ", ctr)
for r in recs:
print(r[0],r[1],r[2],r[3],r[4],sep = "\t")
def insert():
while True:
bno=input("Enter book no:")
bn=input("Enter book name:")
cat=input("Enter category:")
pr=input("Enter price:")
dpur=input("Enter date of purchase:")
st="INSERT INTO BOOK VALUES("+bno+",' "+bn+" ',' "+cat+" ',"+pr+",' "+dpur+" ')"
mcur.execute(st)
ans=input("Do you want to continue y/Y:")
if ans in "nN":
break
mydb.commit()
Book Details Manipulation Using MySQL-Python
def countcatg():
cat=input("Enter category:")
mcur.execute("SELECT * FROM BOOK WHERE CATEGORY='"+cat+"'")
rec=mcur.fetchall()
cnt=mcur.rowcount
print("Count of records with ",cat,"category:",cnt)
Book Details Manipulation Using MySQL-Python
def delbookno():
bno=input("Enter bookno")
str1="SELECT * FROM BOOK WHERE BOOKNO = "+bno+""
mcur.execute(str1)
def countpr(): rec=mcur.fetchone()
pr=input("Enter price:") ctr=mcur.rowcount
st= "SELECT * FROM BOOK WHERE PRICE > "+pr+"" if ctr==0:
mcur.execute(st) print("Record not found")
rec=mcur.fetchall() else:
cnt=mcur.rowcount print("bookno",rec[0])
print(“No. of records with price > ",pr,"is:",cnt) print("bookname",rec[1])
print("category",rec[2])
print("price",rec[3])
print("date of publishing",rec[4])
ans=input("want to delete thisrecord?y/n")
if ans in "yY":
str2="DELETE FROM BOOK WHERE BOOKNO ="+bno+“ "
mcur.execute(str2)
mydb.commit()
Book Details Manipulation Using MySQL-Python
def delname():
bn=input("Enter book name:")
mcur.execute("SELECT * FROM BOOK WHERE BNAME='"+bn+"'")
rec = mcur.fetchall()
ctr = mcur.rowcount
if ctr == 0:
print("Record not found")
else:
for r in rec:
print("bookno",r[0])
print("bookname",r[1])
print("category",r[2])
print("price",r[3])
print("date of publishing",r[4])
ans=input("Do you want to delete the records?y/n")
if ans in "yY":
str2="DELETE FROM BOOK WHERE BNAME ='"+bn+"'"
mcur.execute(str2)
mydb.commit()
Book Details Manipulation Using MySQL-Python
def editbno():
bno=input("Enter bookno")
str1="SELECT * FROM BOOK WHERE BOOKNO ="+bno+""
mcur.execute(str1)
rec=mcur.fetchone()
ctr=mcur.rowcount
if ctr==0:
print("Record not found")
else:
print("bookno",rec[0])
print("bookname",rec[1])
print("category",rec[2])
print("price",rec[3])
print("date of publishing",rec[4])
ans=input("Do you want to edit this record?y/n")
if ans in "yY":
pr=input("Enter new price")
str2="UPDATE BOOK SET PRICE="+pr+" WHERE BOOKNO ="+bno+""
mcur.execute(str2)
mydb.commit()
Book Details Manipulation Using MySQL-Python
while True:
print("\n\nMENU FOR DATA MANIPULATION")
print("1. INSERT NEW RECORDS")
print("2. DISPLAY AND COUNT ALL RECORDS")
print("3. SEARCH & DISPLAY")
print("4. COUNT RECORDS BASED ON A CATEGORY")
print("5. COUNT RECORDS MORE THAN A PRICE")
print("6. DELETE RECORD MATCHING WITH A BOOKNO")
print("7. DELETE RECORD MATCHING WITH BOOKNAME")
print("8: EDIT PRICE OF A RECORD FOR A BOOKNO")
ch = int(input("\nEnter Your Choice (1-8) - "))
if ch == 1:
insert()
elif ch == 2:
showrec()
elif ch==3:
ch1= int(input("1. SEARCH ON BOOK NO\n2. SEARCH ON BOOKNAME\nENTER YOUR
CHOICE(1/2) - "))
if ch1==1:
searchbno()
elif ch1==2:
searchbname()
Book Details Manipulation Using MySQL-Python
elif ch==4:
countcatg()
elif ch==5:
countpr()
elif ch==6:
delbookno()
elif ch==7:
delname()
elif ch==8:
editbno()
ans=input("\nWant to Continue with Data manipulation (y/n) - ")
if ans in "nN":
break
mcur.close()
mydb.close()
MySQL-Python Connectivity Terminology
import mysql.connector
This line imports the MySQL Connector Python module in your program so
the Program can use module’s API to connect MySQL.
mysql.connector.connect()
This method established a connection to the MySQL database from
Python application and returned a MySQL Connection object which
can be used to perform various operations on the MySQL
Database.
connection.is_connected()
Is_connected() is the method of the MySQLConnection class through it
can be verified that wheter python application is connected to MySQL
or not.
connection.cursor()
execute()
This method executes the SQL query and returns a Result Set object
which contains all the rows when the query returns any records from
MySQL .
commit() method to make sure that the commands detailed in the DML
command are implemented in the database.
MySQL-Python Connectivity Terminology
cursor.close()
Using the cursor’s close method the cursor object can be closed. Once the
cursor object is closed noSQL statement can not executed.
connection.close()
MySQL database connection can be closed using the close() method of
Connection class
cursor.fetchall()
Fetch() method fetch all the records present in the result set.
cursor.fetchone()
cursor.fetchone() method is used to fetch single row from the result set.
cursor.fetchmany(n)
cursor.fetchmany(n) method is used to fetch n number of rows from the
result set.
cursor.close()
Using the cursor’s close method the cursor object can be closed. Once the
cursor object is closed noSQL statement can not executed.
connection.close()
MySQL database connection can be closed using the close() method of
Connection class
Assessment
Answer the following
Write the statement required to incorporate MySQL interface with Python
Answer : import mysql.connector
____________ refers to the logical set of records that is fetched from the database
Answer : ResultSet
____________ method will return only one record from the resultset
Answer : fetchone
_________ method invoked through ________ object is used to create the cursor object in
Python
Answer : cursor(), connection object
To check the whether the connection is successful or not _______ method can be used
Answer : is_connected()
A resultset is extracted from the database using the cursor object (that has been already
created) by giving the following statement.
Mydata=cursor.fetchone()
(a) How many records will be returned by fetchone() method?
(b) What will be the datatype of Mydata object after the given command is
executed?
Answer : (a) One record (b) tuple
Assessment
Answer the following
__________________________ #i. query to extract all records from table book
__________________________ #ii. statement to return all records to the result set
__________________________ #iii. statement to get no. of records into an object recs
for r in recs:
print(r[0],r[1],r[2],r[3],sep = "\t")
print("\nTotal records in the table -",ctr)
(a) Fill in the blanks for i, ii and iii
Answer : mycur.execute("SELECT * FROM EMP")
recs = mycur.fetchall()
ctr = mycur.rowcount
(b) What will be the datatype of recs and r objects after the given command is
executed?
Answer : recs - list object
r - tuple object