Interface Python with MySQL
Steps for creating Database
Connectivity Applications
There are mainly seven steps that are followed to
create a database connectivity application.
1. Start Python
2. Import the packages required for database programming
3. Open a connection to the database
4. Create a cursor instance
5. Execute a query
6. Extract data from the result set (in case of SELECT query)
7. Clean up the environment
Start Python
• Open Python using the Python IDLE.
• The MySQL connector must be installed
before it.
• The command to install MySQL Connector on
python is pip install mysql-connector-python
Import the packages required for
database programming
To import the mysql.connector package we need
to issue the following command:
import mysql.connector
or
import mysql.connector as m1
Open a connection to the database
The connect( ) function of mysql.connector establishes
connection to a MySQL database and requires four
parameters, which are:
<connection object> = mysql.connector.connect(host = <hostname> , user
= <username> , passwd = <password> [, database = <database>])
• <hostname> is database server hostname or IP Address
• <username> is the user name for MySQL (default root)
• <password> is the password for MySQL
• <database> is the name of the MySQL database (optional)
Example:
mycon = m1.connect( host='localhost' , user='root' ,
passwd='1234' , database='cs')
Create a cursor instance
A database cursor is a special control structure
that facilitates the row by row processing of
records in the resultset.
cursor = mycon.cursor( )
Execute a query
The resultset refers to a logical set of records
that are fetched from the database by a SQL
query.
cursor.execute(query)
Extract data from the result set
(in case of SELECT query)
If the data is being retrieved from the database using SQL select
command, it is stored in the form of a resultset in the cursor. We
need to extract it from the resultset using any of the fetch
functions.
• data = cursor.fetchall( ) – returns ALL records as per the query in
the form of tuples.
• data = cursor.fetchone( ) – returns ONE record as per the query in
the form of tuple.
• data = cursor.fetchmany(n) – returns 'n' records as per the query in
the form of tuples, where n is the number of records.
• variable = cursor.rowcount – returns the total number of rows
retrieved from the cursor.
Clean up the environment
With the queries that change the data of the
database table, like insert, update and delete
queries it is important to run commit( ) with
the connection object.
mycon.commit( )
• In the end, clean up the environment by
issuing the command:
mycon.close( )
MySQL
create database cs; insert into student
values(101,'Ruhani',76.80,'A','A','Pending'),
use cs;
(102,'George',71.20,'B','A','Submitted'),
(103,'Simran',81.20,'A','B','Evaluated'),
create table student (104,'Ali',61.20,'B','C','Assigned'),
(rollno int(3) primary key, (105,'Kushal',51.60,'C','C','Evaluated'),
name varchar(20), (106,'Arsiya',91.60,'A+','B','Submitted'),
(107,'Raunak',32.50,'F','B','Submitted');
marks decimal(5,2),
grade char(2),
section char(1),
project varchar(15));
Example 1: Display all the records
from the student table.
import mysql.connector as m1
mycon=m1.connect(host='localhost', user='root',
passwd='1234', database='cs')
if mycon.is_connected():
cursor=mycon.cursor()
cursor.execute('select * from student')
data=cursor.fetchall()
print('Total number of rows ',cursor.rowcount)
for row in data:
print(row)
mycon.close()
Example 2: Display first three records
from the student table.
import mysql.connector as m1
mycon=m1.connect(host='localhost', user='root',
passwd='1234', database='cs')
if mycon.is_connected():
cursor=mycon.cursor()
cursor.execute('select * from student')
data=cursor.fetchmany(3)
print('Total number of rows ',cursor.rowcount)
for row in data:
print(row)
mycon.close()
Example 3: Display first two records from the
student table, fetching them one at a time.
import mysql.connector as m1
mycon=m1.connect(host='localhost', user='root',
passwd='1234', database='cs')
if mycon.is_connected():
cursor=mycon.cursor()
cursor.execute('select * from student')
data=cursor.fetchone()
print(data)
data=cursor.fetchone()
print(data)
mycon.close()
Example 4: Display the records of students
where marks are more than 70.
import mysql.connector as m1
mycon=m1.connect(host='localhost', user='root',
passwd='1234', database='cs')
if mycon.is_connected():
cursor=mycon.cursor()
query="select * from student where marks>70"
cursor.execute(query)
data=cursor.fetchall()
for row in data:
print(row)
mycon.close()
Example 5 : Input a name from the user and display
the record of that student from the student table.
import mysql.connector as m1
mycon=m1.connect(host='localhost', user='root', passwd='1234',
database='cs')
if mycon.is_connected():
cursor=mycon.cursor()
n=input('Enter a name ')
query="select * from student where name='%s'" %(n,)
cursor.execute(query)
data=cursor.fetchall()
if cursor.rowcount>0:
for row in data:
print(row)
else:
print('Record does not exist')
mycon.close()
Example 6: Display the records of the students from the student
table whose section and project status is entered by the user.
import mysql.connector as m1
mycon=m1.connect(host='localhost', user='root', passwd='1234',
database='cs')
if mycon.is_connected():
cursor=mycon.cursor()
s=input('Enter section ')
p=input('Enter project status ')
query="select * from student where section='%s' and project='%s'" %(s,p)
cursor.execute(query)
data=cursor.fetchall()
if cursor.rowcount>0:
for row in data:
print(row)
else:
print('Record does not exist')
mycon.close()
Different ways to pass user input in
queries
• Method I:
query="select * from student where section='%s' and project='%s'" %(s,p)
• Method II:
query="select * from student where section='{}' and project='{}'".format(s,p)
• Method III:
query="select * from student where section='{0}' and project='{1}'".format(s,p)
• Method IV:
query="select * from student where section='{x}' and
project='{y}'".format(x=s,y=p)
Example 7: Write a Python script to insert
a record in the student table.
import mysql.connector as m1
mycon=m1.connect(host='localhost', user='root', passwd='1234',
database='cs')
if mycon.is_connected():
cursor=mycon.cursor()
r=int(input('Enter rollno '))
n=input('Enter name ')
m=float(input('Enter marks '))
g=input('Enter grade ')
s=input('Enter section ')
p=input('Enter project status ')
query="insert into student values({},'{}',{},'{}','{}','{}')".format(r,n,m,g,s,p)
cursor.execute(query)
mycon.commit()
print('Record saved')
mycon.close()
Example 8: Write a Python script to update marks of a
student whose rollno is entered by the user.
import mysql.connector as m1
mycon=m1.connect(host='localhost', user='root', passwd='1234',
database='cs')
if mycon.is_connected():
cursor=mycon.cursor()
r=int(input('Enter rollno of student whose marks have to be changed '))
m=float(input('Enter marks '))
query="update student set marks={} where rollno={};".format(m,r)
cursor.execute(query)
mycon.commit()
print('Marks updated')
mycon.close()
Example 9: Write a Python script to delete
a record from the student table.
import mysql.connector as m1
mycon=m1.connect(host='localhost', user='root',
passwd='1234', database='cs')
if mycon.is_connected():
cursor=mycon.cursor()
r=int(input('Enter rollno of student to be deleted '))
query="delete from student where rollno={};".format(r, )
cursor.execute(query)
mycon.commit()
print('Record Deleted')
mycon.close()
SQP 2021 (2 Marks)
Differentiate between fetchone() and fetchall()
methods with suitable examples for each.
fetchall() fetches all the rows of a query result. An empty list is
returned if there is no record to fetch the cursor.
fetchone() method returns one row or a single record at a
time. It will return None if no more rows / records are
available.
(Any example)