PRACTICE MAKES
PERFECT…
COMPUTER
Standard : SCIENCE Day :
XII 1
Interface Python with
SQL
AJAY D (PGT CS) APS 7639605729
This Chapter
Covers…
• Introduction
• Python-MySQL
Connectivity
• Why Python
• Installing MySQL –
Connector
• Establishing Connection
• Creating Cursor Object
• Creating a Database
Operations on a Table in a
• Closing
NutshellCursor and
INTRODUCTI
ON
Database
• Systematic collection of data
• Supports storage and manipulation of information
• Managed by a Database Management System
(DBMS/RDBMS)
• Processing more efficient
AJAY D (PGT CS) APS 7639605729
Storage
Hierarchy
DATABASE DataBa
se
TABLES Table Table-
1 N
RECORDS Record- Record-N
1 Records
FIELDS Fields Fields Fields
AJAY D (PGT CS) APS 7639605729
Database
Servers
• MySQL • MSAccess • Hadoo
• mSQL • MS SQL p
• GadFly Server • Dbase
• Oracle • PostgreSQL III
• Sybase • Mongo DB
• Cassand • Orient DB
ra • Maria DB
••SQLite
S
I B M D B 2
HU NM UG A SUN DA RAM S. •
• FirebirdSql
Informix
Python
supports
•Data Definition Language
(DDL)
•Data Manipulation Language
(DML)
•Data Control Language (DCL)
•Data Query Language (DQL)
•Transaction Control Language
AJAY D (PGT CS) APS 7639605729
…
Data Definition Language
(DDL)
• To define :the
Create To database structure
create tables in theor
database
schema : Alters the structure of the database
Alter
Drop : Delete tables from database
Truncat : Remove all records from a table, also
e release the space occupied by those records
AJAY D (PGT CS) APS 7639605729
…
Data Manipulation Language (DML)
• Modify stored data but not the schema of the database
table.
Insert : Inserts data into a table
Updat : Updates the existing data within a table
e : Deletes all records from a table, but not
Delet the space occupied by them
e
AJAY D (PGT CS) APS 7639605729
…
Data Control Language (DCL)
• To control the access of data stored in a
database
•
Gran controlling
It is used:forGrants privileges
permission in more
to one or the
t database users to perform specific tasks
Revok : Withdraws the access permission
e given by the GRANT statement
AJAY D (PGT CS) APS 7639605729
…
Data Query Language (DQL)
• To retrieve data from a database.
Select : It displays the records from the
table
AJAY D (PGT CS) APS 7639605729
…
Transaction Control Language
(TCL)
• To manage
Commit transactions
: Saves in the
any transaction into the database
databasepermanently
Roll
Save point: :Restores
back the database
Temporarily to last commit
save a transaction state
so that you
can rollback
AJAY D (PGT CS) APS 7639605729
PYTHON-MySQL
CONNECTIVITY
Pytho
DB- MySQ
n
API L
Interfac
e
Front End Back End
Tool Tool
DB-API – Provide a DB Application Programming
Interface
USE OF
PYTHON
• More efficient and faster
• Highly portable to many DB
• Platform-Independent
• Support SQL Cursor and RDBMS
• Take care of Open and Closed connections of DB
• Take care of exceptions and errors on DB
• Python DB-API are compatible with various
databases
• Very easy to migrate and port db application
interfaces
AJAY D (PGT CS) APS 7639605729
RECAPITULAT
ION
• Data Base and its storage
hierarchy
• DB Servers
• DDL, DML,DCL,DQL and TCL
• Python-MySQL connectivity
• Python DB-API
• Use of Python
AJAY D (PGT CS) APS 7639605729
Don’t put too many irons in
the fire
COMPUTER
Standard : SCIENCE Day :
XII 2
Interface Python with
SQL
AJAY D (PGT CS) APS 7639605729
Function of
API
Function of API
Pytho
n
DB- MySQ • Importing API
API L
Interfac module
e
Front End Back End • Acquiring a
Tool Tool
• To establish connection between python
connection with the
and MySQL then require Python DB DB
Interface and API
• DB-API provide minimal standard for • Issuing SQL
working wSHiUtNhMUGDABSUNaDAnRdAM PS.
statements and
y t h o n
stored Procedures
How to connect Python with
MySQL
• The connector is needed to connect Python with Mysql
• To ensure that mysql.connector is installed in the folder where
installed the python
Ex.c:\ProgramFiles\Python37-32\Scripts
If not, to install mysql-connector as
c:\ProgramFiles\Python37-32\Scripts>python –m pip install mysql-
connector
AJAY D (PGT CS) APS 7639605729
Installing
mysql.connector
AJAY D (PGT CS) APS 7639605729
…
If aSnHyUNeMUrGrAoSrUNiDsARoAcMcS.uMrE. wC/ hSEile+91o9- n994i5n4s86t1a9 lling can use the
command c:\ProgramFiles\Python37-32\Scripts>python –m pip3
install mysql-connector
Importing
mysql.connector
Prerequisite for installing mysql.connector
• Download Python 3.x and install
• Download MySQL API and install
• Install MySQL-Python Connector
• To establish connection between MySQL server using
Python
After installing mysql-connector then Import mysql.connector in Python
program
AJAY D (PGT CS) APS 7639605729
Creating Database Connectivity
Applications
Steps to be followed
Step 1 : Start Python
Step 2 : Import the packages required for database
connectivity
Step 3 : Open connection to
database Step 4 : Create a cursor
instance
Step 5 : Execute a query
Step 6 : Extract data from result
set
AJAY D (PGT CS) APS 7639605729
Step 7 : Clean up the
Use of
MySQLdb
Aternative way to connect MySql with Python (instead of
mysql.connector)
• MySQLdb is an python interface for connecting MySQL
•It implements the Python DB-API and is built on top of the
MySQL C API Installing mysqlclient :
pip install mysqlclient or
pip3 install mysqlclient
AJAY D (PGT CS) APS 7639605729
…
After installing mysqlclient, import mysqldb in python program
If any error, it download from http://sourceforge.net/projects/mysql-python or other
web site
SHUNMUGA SUNDARAM S. 99945486
M.E/CSE 19
Importing and Open a connection to
MySql
Importing Connector :
• Import mysql.connector or
• Import mysql.connector as MCR
where, MCR –
mysql.connector object Open a
connection : using the method connect()
<Connection_object>=mysql.connector.connect(host=<host name>,user=‘<user
name>’, passwd=‘<password>’ [,database=‘<database name>’])
Example :
Cn=MCR.connect(host=‘127.0.0.1’,user=‘root’,passwd=‘admin’,databa
se=‘test’) Where, Cn= Connection Object
Host=server’s ip address , user – username on MySQL
pA aSUsNDsAwRAMdS=. Mt.Eh/CeSE p+9a1-9s9s94w548o61r9d of the user , database –
SHUNMUG
RECAPITULAT
ION
• Installing MySQL.Connector
• How to connect Python with MySQL
• Importing mysql.connector
• Creating Database Connectivity
Applications
• Use of MySQLdb
• Importing and Open a connection to
MySql
AJAY D (PGT CS) APS 7639605729
Birds of a feather flock
together…
COMPUTER
Standard : SCIENCE Day :
XII 3
Interface Python with
SQL
AJAY D (PGT CS) APS 7639605729
Installation of
MySQL
SHUNMU UNDARA
G M
…
AJAY D (PGT CS) APS 7639605729
…
AJAY D (PGT CS) APS 7639605729
…
AJAY D (PGT CS) APS 7639605729
…
AJAY D (PGT CS) APS 7639605729
…
AJAY D (PGT CS) APS 7639605729
…
AJAY D (PGT CS) APS 7639605729
…
AJAY D (PGT CS) APS 7639605729
Starting of
MySQL
AJAY D (PGT CS) APS 7639605729
Checking the Current
User
AJAY D (PGT CS) APS 7639605729
ESTABLISHING
CONNECTION
Create Connector Object
Execut • Import mysql.connector as
e Mcr
Querie • Cn=Mcr.connect()
Create Connection s
• Cr=Cn.cursor()
Object
• cr.execute()
• Cr.close()
• Cn.close()
Close Cursor and
Create Cursor Object Connection
AJAY D (PGT CS) APS 7639605729 Objects
…
Practical Implementation-1: To establish connection between Python
and MySql
host=‘localhost’ or host=‘IP address of MySql
Server’
connect() : This method creates a connection to the MySql server and ruturns a MySql
RECAPITULAT
ION
• Installation of MySQL
• Starting of MySQL
• Checking the Current User
• Establishing Connection between Python and
MySql
• Execution Procedures of DB Application
AJAY D (PGT CS) APS 7639605729
A Good Reputation is a Fair
Estate…
COMPUTER
Standard : SCIENCE Day :
XII 4
Interface Python with
SQL
AJAY D (PGT CS) APS 7639605729
CREATING CURSOR
OBJECT
Cursor :
• It will execute all the queries that needed
• It is an abtraction specified in Python DB-API
• It has the ability to have multiple working
environment through the same connection to
the DB
• It will be created by connection.cursor()
• It has the entire life time and all the commands
are executed in the context of DB session
wrapped by the
Steps to establish the
connection
• To create connection object (Cn) by use of mysql.connector.connect()
method
• To create cursor object (Cr) by use of connection.cursor() method
• To execute queries by cursor.execute() method
• Close the Cursor object by cursor.close()
• Close the connection object by connection.close()
• Catch exception if any that may occur during this process
AJAY D (PGT CS) APS 7639605729
Steps to establish the
connection
Mcr.connect Connection
() Request
Cn MySql Connecte
object Connect d
Python or MySQ
Cn.cursor Cursor L
Applicatio () Request D
Python
DB- B
n Cr Cursor
object API Created
Cr.execute( Cr.execute(
AJAY D (PGT CS) APS 7639605729 ) )
Arguments of
Connect()
User Name :
• Use the username to work with MySql Server, Default
Username=‘root’
Password :
• Password of the user work with MySql Server, by default the user
‘root’ has no password
Host Name:
• IP address of the server or Host name of the server
Database Name:
AJAY D (PGT CS) APS 7639605729
• Name of the DB that want to use
CREATING A
DATABASE
To check whether the database exists or not before using the database
Show databases : open mysql command line client and use ‘show
databases;’
AJAY D (PGT CS) APS 7639605729
Create a
database
Practical Implementation-2: To create a new database ‘school’ in MySql
through Python
Show databases
SHUNMUGA SUNDARAM . M E/CSE +91-
9994548619
Understanding the Python MySql DB
Connection
import mysql.connector :
• Import mysql.connector to python program then use this API module
to MySql
• Mysql-connector error object is used to show us an error when fail to
connect databases
• Ex. ER-ACCESS_DENIED_ERROR when username or password is
wrong
mysql.connector.connect() :
• Used toCS)connect
AJAY D (PGT APS 7639605729 the MySql database and accepts required
parameters : host,user,passwd and database
…
Connect() :
• Establishes a connection to the MySQL database from Python
applications
• It returns a MySql Connection object (Cn)
• Throw exception as Database error, if one of the required parameters is
wrong or required db is not exist
Cn.is_connected() :
• To verify whether Python application is connected to MySql
AJAY D (PGT CS) APS 7639605729
…
connection.cursor() :
• It returns a cursor object.
• Using cursor object, can execute SQL queries
• Execute all SQL statements through cursor object
•It interact with the MySql Server using a MySQL connection
object Cursor.execute() :
To traverse over the records in a database
An arbitrary number of cursors can be
created To traverse the records from the
result
AJAY Dsets.
(PGT CS) APS 7639605729
RECAPITULAT
ION
• CREATING CURSOR OBJECT
• Steps to establish the connection
• Arguments of Connect()
• CREATING A DATABASE
• Understanding the Python MySql DB
Connection
AJAY D (PGT CS) APS 7639605729
Fortune favors the
bold…
COMPUTER
Standard : SCIENCE Day :
XII 5
Interface Python with
SQL
AJAY D (PGT CS) APS 7639605729
Practical
Implementation : 3
# To check the database has been created
or not
SHUNM UNDARAM
execute() : To execute all SQL queries from Python and associated with
Practical
Implementation : 4
# To create a table ‘student’ inside the db
‘school’
SH A
* If no error is displayed when the table has been successfully
…
# To verify the structure of table as : desc student
in Mysql prompt
AJAY D (PGT CS) APS 7639605729
Practical
Implementation : 5
# To check the created table ‘student’ in db
‘school’
To display all the tables present inside the database
Implementing DDL
commands
Practical Implementtion-6 : To add a new column ‘marks’ in the
student table
SHUNMUGA
SUNDARAM
* If no error is displayed when the structure of the table has been created
Practical
Implementation : 7
# To view the modified structure of the table
‘student’
M S
+91-
Implementing DML
commands
Practical Implementtion-8 : To insert a record into the table ‘student’ using
python
rowcount : to return number of rows that were affected by
…
• Verify the record has been inserted or not using ‘select’
statement
AJAY D (PGT CS) APS 7639605729
Practical
Implementation : 9
• Insert more number of records in ‘student’ table using
python
UGA S -
S .
Practical
Implementation : 9
• Insert more number of records in ‘student’ table using
python
AJAY D (PGT CS) APS 7639605729
RECAPITULAT
ION
Practical Implementation
• To check the database has been created or not
• To create a table ‘student’ inside the db ‘school’
• To verify the structure of table by ‘desc student’ in Mysql
prompt
• To check the created table ‘student’ in db ‘school’
• To add a new column ‘marks’ in the student table
• To view the modified structure of the table ‘student’
• To insert a record into the table ‘student’ using python
• Verify the record has been inserted or not using ‘select’
AJAY D (PGT CS) APS 7639605729
statement
• Insert more number of records in ‘student’ table using
A good face needs no
paints…
COMPUTER
Standard : SCIENCE Day :
XII 6
Interface Python with
SQL
AJAY D (PGT CS) APS 7639605729
Manage MySQL database Transaction in
Python
Transaction Managed be the following methods by connection
object (Cn) commit() : To commit the transaction in
database Syntax :
Exampl connection.commit()
rollback( e
: To revert : Cn.commit()
the changes, when the transaction is in
) failedSyntax :
Exampl connection.rollback()
autocommit() : By edefault, its value : Cn.rollback()
is
‘false’ Syntax : connection.autocommit()=true/
SHUNMUGA SUNDARAM S. M.E/CSE +91- false
9994E548x6a19 mple : Cn.autocommit()=true
…
Queries Examples
Transact ATM
ion
Executed
successful
Comm : Transaction
it Online
ly
Reservation
Query- Online Purchasing
Transaction
Initiate
1 Other
Transacti Online Fee
Query- on payment
2 Online Fund
Query- Transfer etc.,
3 Any of
.
the Rollbac
queries k
.
AJAY D (PGT CS) APS 7639605729
failed
.
Query-N
Read Operations on a
Table
# To display the records by using the following methods
fetchall() : To display all the records in a table
fetchone() : To display the next record of a query
result set
rowcou : To returns the number of rows that were affected by execute
nt query
It is a read-only attribute
AJAY D (PGT CS) APS 7639605729
Practical Implementation :
10
# To display all the records of the table ‘student’ using
fetchall()
Practical Implementation :
10
# To display all the records of the table ‘student’ using
fetchall()
HUN
M
Practical Implementation :
11
# To display a records of the table ‘student’ using
fetchone()
Practical Implementation :
11
# To display a records of the table ‘student’ using
fetchone()
Practical Implementation :
12
# To display all records of the table ‘student’ using
fetchone()
Selection using ‘where’
clause
# To display records of the table ‘student’ using ‘where’
clause
Deleting
Records
# To delete a record from the table ‘student’ using ‘where’
clause
…
AJAY D (PGT CS) APS 7639605729
Updating
Records
# To update record(s) to the table ‘student’ using ‘where’
clause
SHUNMUGA SUNDARAM S.
M.E/CS
…
AJAY D (PGT CS) APS 7639605729
RECAPITULAT
ION
Practical Implementation
• To check the database has been created or not
• To create a table ‘student’ inside the db ‘school’
• To verify the structure of table by ‘desc student’ in Mysql
prompt
• To check the created table ‘student’ in db ‘school’
• To add a new column ‘marks’ in the student table
• To view the modified structure of the table ‘student’
• To insert a record into the table ‘student’ using python
• Verify the record has been inserted or not using ‘select’
AJAY D (PGT CS) APS 7639605729
statement
• Insert more number of records in ‘student’ table using
Empty vessels make the greatest
noise …
COMPUTER
Standard : SCIENCE Day :
XII 7
Interface Python with
SQL
AJAY D (PGT CS) APS 7639605729
Parameterized Query
Program
• A parameterized query is a query in which placeholders used for
parameters
• The parameter values supplied at execution time.
• That means
Example : parameterized query gets compiled only once.
. Place
nm=input(‘Enter a name to be Holders
(ag , nm)
searched’) ag=int(input(‘Enter age
Sqlquery=“update
to be updated’) student set age=‘ag’ where
name=‘nm’”
Cr.execute(Sqlquery)
.
AJAY D (PGT CS) APS 7639605729
Place Holders : Replace the value(s) to corresponding
column(s)
Updating Records using parameterized
query
Before
Updatation
AJAY D (PGT CS) APS 7639605729
…
S
H
…
After
Updatation
AJAY D (PGT CS) APS 7639605729
Deleting Records using parameterized
query
Practical Implementation : To delete the records of student on the
basis of age fetched from the user at Run-Time
Example : Here I want to delete the records those having age is 23
AJAY D (PGT CS) APS 7639605729
…
Place
Holders
(ag)
AJAY D (PGT CS) APS 7639605729
…
After
Deletion
AJAY D (PGT CS) APS 7639605729
Delete Record(s) using Try … except
block
…
Before
Deletion
After
AJAY D (PGT CS) APS 7639605729 Deletion
CLOSING CURSOR AND
CONNECTION
Closing Cursor
cursor.close() or
Where,
Cr.close()
Cr – Cursor Object
Closing Connection
connection.close() or Cn – Connection Object
Cn.close()
AJAY D (PGT CS) APS 7639605729
RECAPITULAT
ION
Parameterized Query Program
Updating Records using parameterized
query DeletingRecords using
parameterized query Delete Record(s)
using Try … except block CLOSING
CURSOR AND CONNECTION
AJAY D (PGT CS) APS 7639605729
A Teacher is better than two
books …
COMPUTER
Standard : SCIENCE Day :
XII 8
Interface Python with
SQL
AJAY D (PGT CS) APS 7639605729
Operations on a
Table
import mysql.connector as Mcr
Cn=Mcr.connect(host='localhost',user='root',passwd='admin',databa
se='school') Cr=Cn.cursor()
def main():
c='Y'
while(c=='Y'):
print('1. Add Record')
print('2. Update
Record') print('3.
Delete Record')
print('4. Display
Records')
choice=int(input('Enter your
choice : ')) if(choice==1):
addData()
elif
choice==2:
updateData
() elif
choice==3:
deleteData(
) elif
choice==4:
displayData()
def addData():
rno=int(input('Enter roll no
:'))
nm=input('Enter Name of the
Student : ') ag=int(input('Enter age
of the student :')) cty=input('Enter
the city : ') into
qry=("insert mk=int(input('Enter
student(rollno,name,age,city,marks)values(%s,'%s',%s,'%s',%s)"%
(rno,nm,ag,cty,mk,))
mark : '))
Cr.execute(qry)
print(Cr.rowcount, " Record
inserted...") Cn.commit()
AJAY D (PGT CS) APS 7639605729
def updateData():
nm=input("Enter the name to be
searched : ") ag=int(input("Enter the
age to be updated : "))
Cr.execute("Update student set age=%s
where name='%s'"%(ag,nm,))
print(Cr.rowcount,"Record(s)
updated") Cn.commit()
AJAY D (PGT CS) APS 7639605729
def deleteData():
ag=int(input("Enter the age of the student whose record is to be
deleted : ")) Cr.execute("delete from student where age=%s"%(ag,))
print(Cr.rowcount,"Record(s) Deleted...")
Cn.commit()
def
displayData():
Cr.execute("select * from
student") for i in Cr.fetchall():
print(i)
main(
AJAY D (PGT CS) APS 7639605729
)
Cn.close()
Cr.close
The pen is mightier than the
sword…
COMPUTER
Standard : SCIENCE Day :
XII 9
Interface Python with
SQL
AJAY D (PGT CS) APS 7639605729
UNSOLVED QUESTION AND
ANSWER
Unsolved
Questions
1. Explain the following fetchone(), fetchall() and
rowcount()
2. Significance of connecting Python with MySQL
3. Use of connect() function
4. Steps for establishing MySql with Python
5. Transaction keywords used in MySql-Python
connectivity Share Your
Knowledge…
6. Significance of using execute() function
7. Commit() and Rollback()
8. Which function is used to connect to db?
10. Which function is used to read one record from
9. Which function is used to run the SQL query?
the db?
PSHrUoNMgUrGaA SmUNsDARaArMeS. aM.sE/WCSEo+r9k1-