MYSQL WITH PYTHON INTERFAcy
(ONLY FOR PROJECT AND PRACT Cay
LEARNING OUTCOMES
After going through this chapter students will be able to:
+ understand the need of MySQL with python connectivity
+ apply the installation steps
differentiate between various components and method of python connectivity
list all the types of errors which occures while connecting
+ experiment with the SQL command from python environment
SEAT EMER A NE RN EON CA I 8 ga
Installation Introduction 2. PyMySQL
Python has many API's which can interact with Pip install PYMySQL
various databases. The Python standard for 3. MySQLDB
database interfaces is the Python DB-API. Most
Python database interfaces adhere to this standard. 5, OurSQL
We need to download a separate DB API module ai
4, Mysqlclient
for each type of database software. Same way we can install other libraries for b®
isite for the Python connectivity with Connection.
Meo database: * . We have to change just the connectors name
install the M; poe
1. Firstly, we need to install the MySQL Server. F¢ Revco ae
For installation, refer to this link:
import MySQLdb
huips://dev.mysql.com/downloads/ db = MySQLdb.connect{host="localhost
installer uuser="root” password="sms",db="test")
2. Secondly, we need python API for connection. For mysql connector
For installation we need to write the given import mysql.connector
statement on command prompt: db = mysql.connector.connect(host="Iocalhos,
pip install MySQLclient
rt
user="root" password="sms",do~ ve
MySQL database support to our applications. For pymysql
1. For installation of MySQL Connector in import pymysql
Python use the command; db = pymysql.connect (host="localhost,
yes)
{pip install mysql-connector-python] user="root" password="sms",db~
2are eer EEE
MYSQL with Python Interface 63
IMPORTANT TERMS & DEFINITIONS
1. Pymysal. Tt is an interface used for connectin
implements the Python Database API 2,0.
To import the module, we need to write :
import pymysql
8 the MySQL database server from Python. It
For example:
db = pymysql.connect(host="localhost,"
user="root" password="sms",db="rachna")
host="localhost", # your host, usually localhost
user="root", # your usemame of mysql_ (normally
default name is root
password="sms" # your mysql password
db="rachna" _—# Test is the name of the database
3. cursor(), The cursor() method of the pymysql connections object is used to work with the database.
The syntax is as follows:
[cursor name] = [connection object name].cursor()
For example:
cur=db.cursor()
4. execute(), This method is used to execute the SQL statement with the database cursor object.
Syntax:
results_variable = cursor_handle.execute
For example:
cur.exceute("SQL Statement") ‘
5. fetchone(), It fetches the single row from the result set. A result set is an object that is returned
when a cursor object is used to query a table.
For example: cur.execute("Select * from Tablename")
Variable=cur.fetchone() an :
6. fetchmany(), This method returns blocks of results according to a set limit. This method requires
the desired number of records to be passed as an argument.
For example: curexecute("Select * from Tablename")
Variable~cur.fetchmany(10) # fetch first 10 records
7. fetchall(), It fetches all the rows in a result set. If eee rows ene
the result set, then it retrieves the remaining rows from the resul
For example: curexecute("Select * from Tablename")
Variable=cur.fetchall()
ready been extracted from64 Fegecher euek® Computer Science (Python)—12
i the number of rows that were affece,
! 8. rowcount). This is a read-only attribute and returns by
execute method. .
For example: curexecute("Select * from Tablename")
Variable=cur.rowcount()
9. commit(). This command is used to save the changes in the database.
For example: db.commit() i
10, rolllack() Iti used to cancel all the changes made to the database, and it only works with Dy
Statements, ie. insert, delete or update.
For example: db.rollback()
11. close(). This method is used to close the database connection object which we have created,
For example: db.close()
Errors. The MYSQL DB API defines some errors that must exist in each database module. Lig
of exceptions are given below:
12.
(| Exception Description a
@ InterfaceError. When the database connection fails for some reason, MySQLdb
| will raise an InterfaceError. This may be caused by problems in
the interface anywhere in the connection process.
| (® | PatabaseError: | When thee is a problem with the MySQL database itself. @
[ DatabaseError is thrown,
(iif) DataError:
This exception is raised du
data (For example,
ue to problems with the processed
| ‘numeric value out of range, division by |
ee
{ay |
| |
iy
|
|) | imtegrityError. database i
involved (for example a foreign key check fap
duplicate key, and so on), this exception js fe |
This exception is raised when there is an inges-————
MySQL database itself (for example. =
_ transaction is out of sync, and so on),
Exception raised for actual Programmi:
table snot found or areny ore ee Ste (or example a
MySQL statement, a wrong number of Parameters error in the
and so on.). 1S specified,
MySQL for Python raises #1 Ption. When
oF database API that i nt supported is wget ® Method
feqesing tansaction-onented function mg" exampt,
are not available. ictions
eaeMYSQL with Python Interface 65
Example of exception handling white connecting
import pymysq]
try
mydb = pymysql.connect(host ="localhost’, us ‘Oot’, passwd = ‘root’, db
1 ul ‘root’
er = ‘root’,
cur = mydb.cursor()
statement = """SELECT * FROM student
cur. execute (statement)
results = cur.fetchall()
print (results)
except MySOLdb.Error as e:
print ("An error has been passed. %s" xe)
For multiple errors we can write :
except (MySOLdb.OperationalError, MySOLdb.Progranmingérror)as e:
Python DB APIv2.0
(PEP 249)
SOLVED QUESTION BANK
Very Short Answer Type Questions [1 Mark]
1. Which method is used to get the row-id of the last modified row?
Ans, cursor.lastrowid
2. Which method of cursor class is used to fetch limited rows from the table?
Ans. cursor.fetchmany(SIZE)
3. Which method of cursor clas
Ans,
used to insert or update multiple rows using a single query?
cursor.executemany(query, rows)
4. Which method is used to Commit pending transaction to the database in Python?
Ans. connection.commit() Sorerae
ted after any of the
5 Wa Is used to get the number of rows affect
lich method of cursor class papoapieles
lnsert/update/delete database operation execu
Ans, cursorrowscountAns.
Ans.
Ans.
Ans.
10.
Ans.
ience (Python) —12
eve the executed database function or stored procedure regu},
Tagether with® Computer S
Which method is used to retri
in Python?
cursorstored_results()
Which method of cursor class is used to execute database function or stored procedure in
Python?
cursor callfune("procedureName’ [parameters,])
Which exception is raised when the relational integrity of the database is affected in Python»
IntegrityError
‘Complete the code:
import ae
db = MySOLab.
root”, passwd
cur + db.cursor()
print ("Database connected" cur)
db.close()
MySQLdb and connect
_(host= "localhost", use
test")
Which method is used for closing the connection with database is?
Closet)
Short Answer Type Questions [2/3 Marks]
Me
Ans.
12.
Ans.
13.
Ans.
14.
Ans.
How many parameters are required toconnect() method? Name them.
Four parameters are required for the connectivity.
i.e. Hostname, Username, Password and Database name,
Write the difference between fetchone() and fetchmany() method.
Fetchone(). It fetches the single record or row from the resultset,
Fetchmany(). This method returns blocks of results according to a set limit,
What is Data Error?
This exception is raised due to problems with the processed data (for example, numeric value
of range, division by zero, and so on). .
Write the python script to connect to the data
connection.
and print the cursor statement for!
import _pymysql
ty:
db = pymysql. connect (host="localhost*
cur = db. cursor()
print("Database connected" cur)
cur. close()
susers"root",passud="root", db="rach')MYSQL with Python Interface 67
db.close()
‘except Exception as e:
print( "Database open error")
15, Write the python script to connect the database,
following field (empno,name and salary), Also, i
import pynysql
Le.test and create the table emp21 with the
insert the row.
db = pymysql. connect (host="localhost*
suser
cur = db.cursor()
‘oot, passud="root”,db="rachna”)
munrow=cur.execute( ‘CREATE TABLE emp2i(empno INT, name VARCHAR(20), salary INT): ")
cur-execute("INSERT INTO emp2 VALUES (1, ‘Neha’, 9000);")
db.commit ()
cur.close()
db.close()
except Exception as e:
print("Error",e)
16. Write the python script that read the whole data from the table emp and display alll the
records.
Ans. import pymysql
db = pymysql.connect(host="Localhost" ,user="root", passwd="root”,
cur = db.cursor()
numrow=cur.execute("SELECT * FROM emp")
print (cur. fetchal1())
db. close()
Write the python script to read the content from .csv file (Comma Seperated Values) i.e
"Student.csv" and then transfer the content to the SQL Table.
import csv
import pymysq]
data-{]
with open('E:\workshop\Student.csv', x") as csvFile:
Treader = csv. reader(csvFile)
for row in reader:
data. append( row)
db = pymysql. connect (host='
Cur = db.cursor()
for row in data:
Sql = “insert into Student VALUES("+rou[0]+",
Nunrow=cur. execute(sql)
db. commit ()
Tuntow=cur.execute("SELECT * FROM Student")
Student-cur. fetchal1()
Print (Student)
.close()
rachna")
n,
Ans,
root", passud
localhost", use!
lea leet6B Together weh® Computer Science (Python)—12
18. Write the python script to display all the records from the table student using for loop,
Ans. import. pynysql . .
> = pymysql.connect (host "localhost" ,user="root” ,password="root™, db="rachna")
cur = db. cursor()
numrowscur.execute("SELECT * FROM Student")
Student=cur. fetchall()
print(*Student Number\tStudent Nane\tStudent Marks")
for record in Student:
print (record(0),"\t\t", record[1], "\t\t", record[2])
db. close()
Long Answer Type Questions [4 Marks]
V
. Write the python function to accept the rollno as parameter and find out whether record
Present in the table or not.
Ams. def check_name_present (roL1no)
db=pymysql.connect(host="localhost", user="root", passwd="root", db="rachna");
cur=db. cursor()
cur.execute("select * from student")
Student=cur, fetchall()
for k in Student:
if(int(k[0])=-rolino) :
print ("Record found", k)
break
else:
print("Not Found")
20. Write the python function to accept the name as parameter and find out whether record
Present in the table or not. (Assuming that table already exists)
Ans. def check_name_present (nane) :
db=pymysql.connect (host="localhost”, users"root", passud="root", dbs"rachna"):
cur=db.cursor()
cur.execute(" select * from student")
Student=cur. fetchal()
for k in Student:
i€((k(1]) ==name) :
print("Record found", k)
break
else:
print("Not Found")
1. Write function insert() to insert the new row in table student. The function will take ti
values as parameter.
» def insert(n,na,ma):
db=pymysql. connect (host="localhost”, user="root",
Passwd="root", db="rachna")i
ib. cursor()7 MYSQL with Python Interface 69
query = “INSERT INTO student(rolino, name,
cur-execute (query) ’
do.conmit()
print("Row inserted")
2, Write a function update() to accept th,
: to the passed values, ‘Assuming that wt iad Loe, update the record according
‘ans. def update(n,na,ma): =
db=pymysql..connect (host="localhost™,
cur=db. cursor()
query = “UPDATE student SET name='%s°, mark
cur. execute(query)
db. commit()
print("Row Updated")
23, Write the python function delete() to delete the record In the student table according to the
rolino passed as parameter.
Ans. import. pymysql
def delete(n):
db=pymysql. connect (host="localhost'
cur-db. cursor()
query = "DELETE FROM student WHERE rollno="%s'* % n
cur. execute (query)
db. commit ()
print(“Record Deleted")
no=int(input("Enter the student Number") )
delete(no)
24. WAF delrecord(n) to read the student number as parameter and delete the record in student
table,
Aus. def delrecord(n):
ty:
query = “DELETE FROM stud WHERE rollno="%s'" % n
cx execute(query)
nlscr.rowcount
if n1!=0:
db. commit ()
print ("Record Deleted")
*Marks)VALUES ("Rs", ts", '%5')" 4 (n, na, ma)
User="root", passwd="root", db="rachna");
iS’ WHERE rollno="%s'" % (na,ma,n)
‘rachna");
users"root", passud="root",
else:
print("Record not found")
except:
Print(*Record not found or any other exror")
ain
osint(input(“Enter the Rollno to be Searched *
Selrecord(no)
)