PRACTICE MAKES PERFECT…
COMPUTER SCIENCE
Standard : XII Day : 1
Interface Python with SQL
S.Shunmuga Sundaram, M.E/CSE
This Chapter Covers…
• Introduction
• Python-MySQL Connectivity
• Why Python
• Installing MySQL – Connector
• Establishing Connection
• Creating Cursor Object
• Creating a Database
• Closing Cursor and Connection
• Operations on a Table in a Nutshell
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
INTRODUCTION
Database
• Systematic collection of data
• Supports storage and manipulation of information
• Managed by a Database Management System (DBMS/RDBMS)
• Processing more efficient
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Storage Hierarchy
DATABASE DataBase
TABLES Table1 Table-N
RECORDS Record-1 Record-N Records
FIELDS Fields Fields Fields
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Database Servers
• MySQL • MSAccess • Hadoop
• mSQL • MS SQL Server • Dbase III
• GadFly • PostgreSQL
• Oracle • Mongo DB
• Sybase • Orient DB
• Cassandra • Maria DB
• SQLite • FirebirdSql
• IBM DB2
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
• Informix
Python supports
• Data Definition Language (DDL)
• Data Manipulation Language (DML)
• Data Control Language (DCL)
• Data Query Language (DQL)
• Transaction Control Language (TCL)
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
…
Data Definition Language (DDL)
• To define the database structure or schema
Create : To create tables in the database
Alter : Alters the structure of the database
Drop : Delete tables from database
Truncate : Remove all records from a table, also release the space
occupied by those records
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
…
Data Manipulation Language (DML)
• Modify stored data but not the schema of the database table.
Insert : Inserts data into a table
Update : Updates the existing data within a table
Delete : Deletes all records from a table, but not the space
occupied by them
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
…
Data Control Language (DCL)
• To control the access of data stored in a database
• It is used for controlling privileges in the database
Grant : Grants permission to one or more users to
perform specific tasks
Revoke : Withdraws the access permission given by the
GRANT statement
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
…
Data Query Language (DQL)
• To retrieve data from a database.
Select : It displays the records from the table
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
…
Transaction Control Language (TCL)
• To manage transactions in the database
Commit : Saves any transaction into the database permanently
Roll back : Restores the database to last commit state
Save point : Temporarily save a transaction so that you can rollback
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
PYTHON-MySQL CONNECTIVITY
Python
DB-API MySQL
Interface
Front End Tool Back End Tool
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
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
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
RECAPITULATION
• Data Base and its storage hierarchy
• DB Servers
• DDL, DML,DCL,DQL and TCL
• Python-MySQL connectivity
• Python DB-API
• Use of Python
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Don’t put too many irons in the fire
COMPUTER SCIENCE
Standard : XII Day : 2
Interface Python with SQL
S.Shunmuga Sundaram, M.E/CSE
Function of API
Function of API
Python DB-API MySQL • Importing API module
Interface • Acquiring a connection
Front End Tool Back End Tool with the DB
• To establish connection between python and
• Issuing SQL statements
MySQL then require Python DB Interface and API and stored Procedures
• DB-API provide minimal standard for working • Closing the connection
with DB and Python
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
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
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Installing mysql.connector
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
…
If any error
SHUNMUGA is occur
SUNDARAM while+91-9994548619
S. M.E/CSE on installing 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
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
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
Step 7 : Clean up the environment
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
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
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
…
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. M.E/CSE +91-9994548619
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’,database=‘test’)
Where, Cn= Connection Object
Host=server’s ip address , user – username on MySQL
passwd=
SHUNMUGA the password
SUNDARAM S. M.E/CSE +91-9994548619 of the user , database – user defined DB or built-in DB
RECAPITULATION
• 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
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Birds of a feather flock together…
COMPUTER SCIENCE
Standard : XII Day : 3
Interface Python with SQL
S.Shunmuga Sundaram, M.E/CSE
Installation of MySQL
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
…
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
…
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
…
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
…
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
…
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
…
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
…
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Starting of MySQL
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Checking the Current User
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
ESTABLISHING CONNECTION
Create Connector Object
Execute • Import mysql.connector as Mcr
Queries • Cn=Mcr.connect()
• Cr=Cn.cursor()
Create Connection Object • cr.execute()
• Cr.close()
• Cn.close()
Close Cursor and
Create Cursor Object Connection Objects
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
…
Practical Implementation-1: To establish connection between Python and MySql
host=‘localhost’ or host=‘IP address of MySql Server’
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
connect() : This method creates a connection to the MySql server and ruturns a MySql Connection Object
RECAPITULATION
• Installation of MySQL
• Starting of MySQL
• Checking the Current User
• Establishing Connection between Python and MySql
• Execution Procedures of DB Application
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
A Good Reputation is a Fair Estate…
COMPUTER SCIENCE
Standard : XII Day : 4
Interface Python with SQL
S.Shunmuga Sundaram, M.E/CSE
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
connection
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
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
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Steps to establish the connection
Mcr.connect() Connection Request
Cn object MySql Connected
Connector
Python MySQL
Cn.cursor() Cursor Request
Application DB
Python DB-
Cr object API Cursor Created
Cr.execute() Cr.execute()
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
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:
• Name of the DB that want to use
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
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;’
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Create a database
Practical Implementation-2: To create a new database ‘school’ in MySql through Python
Show databases
SHUNMUGA SUNDARAM S. 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 to connect the MySql database and accepts required parameters :
host,user,passwd and database
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
…
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
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
…
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 sets.
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
RECAPITULATION
• CREATING CURSOR OBJECT
• Steps to establish the connection
• Arguments of Connect()
• CREATING A DATABASE
• Understanding the Python MySql DB Connection
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Fortune favors the bold…
COMPUTER SCIENCE
Standard : XII Day : 5
Interface Python with SQL
S.Shunmuga Sundaram, M.E/CSE
Practical Implementation : 3
# To check the database has been created or not
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
execute() : To execute all SQL queries from Python and associated with Cursor object
Practical Implementation : 4
# To create a table ‘student’ inside the db ‘school’
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
* If no error is displayed when the table has been successfully created
…
# To verify the structure of table as : desc student in Mysql prompt
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Practical Implementation : 5
# To check the created table ‘student’ in db ‘school’
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
To display all the tables present inside the database ‘school’
Implementing DDL commands
Practical Implementtion-6 : To add a new column ‘marks’ in the student table
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
* If no error is displayed when the structure of the table has been created successfully
Practical Implementation : 7
# To view the modified structure of the table ‘student’
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Implementing DML commands
Practical Implementtion-8 : To insert a record into the table ‘student’ using python
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
rowcount : to return number of rows that were affected by execute()
…
• Verify the record has been inserted or not using ‘select’ statement
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Practical Implementation : 9
• Insert more number of records in ‘student’ table using python
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Practical Implementation : 9
• Insert more number of records in ‘student’ table using python
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
RECAPITULATION
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’ statement
Insert
• SHUNMUGA more number of records in ‘student’ table using python
SUNDARAM S. M.E/CSE +91-9994548619
A good face needs no paints…
COMPUTER SCIENCE
Standard : XII Day : 6
Interface Python with SQL
S.Shunmuga Sundaram, M.E/CSE
Manage MySQL database Transaction in Python
Transaction Managed be the following methods by connection object (Cn)
commit() : To commit the transaction in database
Syntax : connection.commit()
Example : Cn.commit()
rollback() : To revert the changes, when the transaction is in failed
Syntax : connection.rollback()
Example : Cn.rollback()
autocommit() : By default, its value is ‘false’
Syntax : connection.autocommit()=true/false
Example
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619 : Cn.autocommit()=true
…
Queries Examples :
Transact Executed Commit ATM Transaction
ion successfully Online Reservation
Online Purchasing
Query-1 Online Fee payment
Initiate Transaction
Query-2 Other
Transaction Online Fund Transfer etc.,
Query-3
.
.
. Any of the
Query-N queries Rollback
failed
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
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
rowcount : To returns the number of rows that were affected by execute query
It is a read-only attribute
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Practical Implementation : 10
# To display all the records of the table ‘student’ using fetchall()
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Practical Implementation : 10
# To display all the records of the table ‘student’ using fetchall()
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Practical Implementation : 11
# To display a records of the table ‘student’ using fetchone()
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Practical Implementation : 11
# To display a records of the table ‘student’ using fetchone()
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Practical Implementation : 12
# To display all records of the table ‘student’ using fetchone()
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Selection using ‘where’ clause
# To display records of the table ‘student’ using ‘where’ clause
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Deleting Records
# To delete a record from the table ‘student’ using ‘where’ clause
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
…
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Updating Records
# To update record(s) to the table ‘student’ using ‘where’ clause
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
…
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
RECAPITULATION
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’ statement
Insert
• SHUNMUGA more number of records in ‘student’ table using python
SUNDARAM S. M.E/CSE +91-9994548619
Empty vessels make the greatest noise …
COMPUTER SCIENCE
Standard : XII Day : 7
Interface Python with SQL
S.Shunmuga Sundaram, M.E/CSE
Parameterized Query Program
• A parameterized query is a query in which placeholders used for parameters
• The parameter values supplied at execution time.
• That means parameterized query gets compiled only once.
Example :
. Place Holders
nm=input(‘Enter a name to be searched’) (ag , nm)
ag=int(input(‘Enter age to be updated’)
Sqlquery=“update student set age=‘ag’ where name=‘nm’”
Cr.execute(Sqlquery)
.
Place Holders : Replace the value(s) to corresponding column(s)
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Updating Records using parameterized query
Before Updatation
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
…
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
…
After Updatation
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
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
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
…
Place Holders
(ag)
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
…
After Deletion
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Delete Record(s) using Try … except block
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
…
Before Deletion
After Deletion
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
CLOSING CURSOR AND CONNECTION
Closing Cursor
cursor.close() or Cr.close()
Where,
Cr – Cursor Object
Closing Connection
connection.close() or Cn.close() Cn – Connection Object
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
RECAPITULATION
Parameterized Query Program
Updating Records using parameterized query
Deleting Records using parameterized query
Delete Record(s) using Try … except block
CLOSING CURSOR AND CONNECTION
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
A Teacher is better than two books …
COMPUTER SCIENCE
Standard : XII Day : 8
Interface Python with SQL
S.Shunmuga Sundaram, M.E/CSE
Operations on a Table
import mysql.connector as Mcr
Cn=Mcr.connect(host='localhost',user='root',passwd='admin',database='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')
print('5.
SHUNMUGA SUNDARAM Exit')
S. M.E/CSE +91-9994548619
choice=int(input('Enter your choice : '))
if(choice==1):
addData()
elif choice==2:
updateData()
elif choice==3:
deleteData()
elif choice==4:
displayData()
elif choice==5:
print('Exiting')
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
break
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 : ')
mk=int(input('Enter mark : '))
qry=("insert into student(rollno,name,age,city,marks)values(%s,'%s',%s,'%s',%s)"%(rno,nm,ag,cty,mk,))
Cr.execute(qry)
print(Cr.rowcount, " Record inserted...")
Cn.commit()
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
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()
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
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()
Cr.close()
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619
Cn.close()
The pen is mightier than the sword…
COMPUTER SCIENCE
Standard : XII Day : 9
Interface Python with SQL
S.Shunmuga Sundaram, M.E/CSE
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
6. Significance of using execute() function Share Your Knowledge…
7. Commit() and Rollback()
8. Which function is used to connect to db?
9. Which function is used to run the SQL query?
10. Which function is used to read one record from the db?
Programs are as Worksheet…
SHUNMUGA SUNDARAM S. M.E/CSE +91-9994548619