INTERFACE PYTHON WITH
MYSQL
Introduction
Every application required data to be stored for future
reference to manipulate data. Today every application
stores data in database for this purpose
For example, reservation system stores passengers
details for reserving the seats and later on for sending
some messages or for printing tickets etc.
In school student details are saved for many reasons
like attendance, fee collections, exams, report card etc.
Python allows us to connect all types of database like
Oracle, SQL Server, MySQL.
In our syllabus we have to understand how to connect
Python programs with MySQL
Pre-requisite to connect Python with
MySQL
Before we connect python program with any database
like MySQL we need to build a bridge to connect
Python and MySQL.
To build this bridge so that data can travel both ways
we need a connector called “mysql.connector”.
We can install “mysql.connector” by using following
methods:
At command prompt (Administrator login)
Type “pip install mysql.connector” and press enter
(internet connection in required)
This connector will work only for MySQL 5.7.3 or later
Or
Open https://dev.mysql.com/downloads/connector/python/”
download mysql connector
Connecting to MySQL from Python
Once the connector is installed you are ready to
connect your python program to MySQL.
The following steps to follow while connecting your
python program with MySQL
Open python
Import the package required (import mysql.connector)
Open the connection to database
Create a cursor instance
Execute the query and store it in result set
Extract data from result set
Clean up the environment
Steps to Connect to MySQL Database in Python
1. Install MySQL connector module
Use the pip command to install MySQL connector Python.
pip install mysql-connector-python
2. Import MySQL connector module
Import using a import mysql.connector statement so you can use this module’s methods to communicate with the MySQL
database.
3. Use the connect() method
Use the connect() method of the MySQL Connector class with the required arguments to connect MySQL. It would return
a MySQLConnection object if the connection established successfully
4. Use the cursor() method
Use the cursor() method of a MySQLConnection object to create a cursor object to perform various SQL operations.
5. Use the execute() method
The execute() methods run the SQL query and return the result.
6. Extract result using fetchall()
Use cursor.fetchall() or fetchone() or fetchmany() to read query result.
7. Close cursor and connection objects
use cursor.close() and connection.close() method to close open connections after your work completes
Importing mysql.connector
import mysql.connector
Or
import mysql.connector as ms
Here “ms” is an alias, so every time we can use “ms” in
place of “mysql.connector”
Open a connection to MySQL Database
To create connection, connect() function is used
Its syntax is:
connect(host=<server_name>,user=<user_name>,
passwd=<password>[,database=<database>])
Here server_name means database servername, generally
it is given as “localhost”
User_name means user by which we connect with mysql
generally it is given as “root”
Password is the password of user “root”
Database is the name of database whose data(table) we
want to use
Example: To establish connection with MySQL
is_connected() function returns
true if connection is established
otherwise false
“mys” is an alias of package “mysql.connector”
“mycon” is connection object which stores connection established with MySQL
“connecStA(C)” FunAtiRoDnWisAJu, sPeGdT(CtoS),cKoVnnNeOc.t1 wTEiZthPUmR ysql by specifying parameters
Table to work (emp)
Creating Cursor
It is a useful control structure of database connectivity.
When we fire a query to database, it is executed and
resultset (set of records) is sent over the connection
in one go.
We may want to access data one row at a time, but
query processing cannot happens as one row at a time,
so cursor help us in performing this task. Cursor stores
all the data as a temporary container of returned data
and we can fetch data one row at a time from Cursor.
Creating Cursor and Executing Query
TO CREATE CURSOR
Cursor_name = connectionObject.cursor()
For e.g.
mycursor = mycon.cursor()
TO EXECUTE QUERY
We use execute() function to send query to connection
Cursor_name.execute(query)
For e.g.
mycursor.execute(“select * from emp‟)
Example - Cursor
Output shows cursor is created and query is fired and stored, but no data is
coming. To fetch data we have to use functions like fetchall(), fetchone(),
fetchmany() are used
Fetching(extracting) data from ResultSet
To extract data from cursor following functions are used:
fetchall() : it will return all the record in the form of
tuple.
fetchone() : it return one record from the result set. i.e.
first time it will return first record, next time it will return
second record and so on. If no more record it will return
None
fetchmany(n) : it will return n number of records. It no
more record it will return an empty tuple.
rowcount : it will return number of rows retrieved from
the cursor so far.
Example fetchall()
:3
Example fetchall()
:3
Example 4: fetchone()
Example 5: fetchmany(n)
Guess the output
Parameterized Query
We can pass values to query to perform dynamic
search like we want to search for any employee
number entered during runtime or to search any
other column values.
To Create Parameterized query we can use various
methods like:
Concatenating dynamic variable to query in which
values are entered.
String template with % formatting
String template with {} and format function
Concatenating variable with query
String template with %s formatting
In this method we will use %s in place of values to
substitute and then pass the value for that place.
String template with {} and format()
String template with {} and format()
In this method in place of %s we will use {} and to
pass values for these placeholder format() is used.
Inside we can optionally give 0,1,2… values for e.g.
{0},{1} but its not mandatory. we can also optionally
pass named parameter inside {} so that while passing
values through format function we need not to
remember the order of value to pass. For e.g.
{roll},{name} etc.
String template with {} and format()
String template with {} and format()
Methods to manage MySQL database
transactions in python
Commit:MySQL connection.commit() method sends a commit
statement to the MySQL Server,commiting the current transactions.
The COMMIT command saves all the transactions to the database.
Rollback: MySQL connection.rollback() method revert the changes
made by the current transactions.
Inserting data in MySQL table from Python
INSERT and UPDATE operation are executed in the
same way we execute SELECT query using execute()
but one thing to remember, after executing insert or
update query we must commit our query using
connection object with commit().
For e.g. (if our connection object name is mycon)
mycon.commit()
BEFORE PROGRAM EXECUTION
Example : inserting data
AFTER PROGRAM EXECUTION
Example: Updating record
CODE
#To display
import mysql.connector as mys
mycon=mys.connect(host='localhost',user='root',
password='root',
database='office')
mycursor=mycon.cursor()
mycursor.execute("select*from emp")
mydata=mycursor.fetchall()
r=mycursor.rowcount
print("Total no. of rows",r)
for i in mydata:
print (i[0],i[1],i[2],i[3],i[4],i[5],sep=": ")
#to search particular record
import mysql.connector as mys
mycon=mys.connect(host='localhost',user='root',
password='root',
database='office')
mycursor=mycon.cursor()
e=int(input("Enter E_CODE to be searched"))
query="select * from emp where E_code=%s"%(e,)
mycursor.execute(query)
mydata=mycursor.fetchone()
if mydata!=None:
print(mydata)
else:
print("No such employee data")
#to search multiple records
import mysql.connector as mys
mycon=mys.connect(host='localhost',user='root',
password='root',
database='office')
mycursor=mycon.cursor()
e=int(input("Enter E_CODE to be searched"))
f=input("Enter employee name to be searched")
query="select * from emp where E_code='%s'or name='%s'"%(e,f,)
mycursor.execute(query)
mydata=mycursor.fetchall()
if mydata!=None:
for i in mydata:
print(i)
else:
print("No such employee data")
**#TO INSERT,DELETE,UPDATE,ALTER,SEARCH WITH MENU DRIVEN
import mysql.connector
db=mysql.connector.connect(host="localhost",
user="root",
password="root",
database="dps")
con=db.cursor()
con.execute("create table student(Rno int primary key,Class int,Name
varchar(15),Marks int)")
db.commit()
def insert():
ch="y"
while True:
r=input("ENTER R.NO ")
c=input("ENTER Class ")
n=input("ENTER Name ")
m=input("Enter Marks ")
try:
st="insert into student VALUES(%s,%s,%s,%s)"
val=(r,c,n,m)
con.execute(st,val)
db.commit()
except:
print("Data not updated")
db.rollback()
ch=input("Do you want to insert more record....y/n")
if ch=='N'or ch=='n':
break
def delete():
f=0
ch='y'
while True:
con.execute("select * from student")
data=con.fetchall()
print()
print("Total number of rows:",con.rowcount)
print()
print("Student Data:")
for i in data:
print(i)
s=input("Choose the Roll no to be deleted")
try:
con.execute("delete from student where rno=%s" %s)
db.commit()
except:
print("Data not updated")
db.rollback()
con.execute("select * from student")
data=con.fetchall()
if data!=None:
for i in data:
if i[0]==s:
#print("Remaining data is")
print(i,sep=" ")
print("Data deleted from database")
f=1
if f==0:
print("wrong input")
else:
print("Record is not available")
ch=input("Do you want to delete more record....y/n")
if ch=='N'or ch=='n':
break
def update():
r=input("Choose the Rollno. to be updated")
name=input("Enter name")
try:
con.execute("update student set name='{}' where rno={}".format(name,r))
except:
print("Data not updated")
db.rollback()
con.execute("select*from student")
data=con.fetchall()
if data!=None:
print(data)
else:
print("Record is not available")
def search():
r=input("Choose the Rollno. to be searched")
con.execute("select * from student where rno=%s" %r)
data=con.fetchone()
if data!=None:
print(data)
else:
print("Record is not available")
def display():
con.execute("select*from student")
data=con.fetchall()
if data!=None:
for i in data:
print(i,sep=" : ")
else:
print("Record is not available")
def menu():
while True:
print("Database operations Implementation")
print("1 - To insert new Record")
print("2 - To delete Record")
print("3 - To update any record")
print("4 - To Search")
print("5 - To Display")
print("6 - Exit")
ch = int(input("Enter the your choice:"))
if ch==1:
insert()
elif ch==2:
delete()
elif ch==3:
update()
elif ch==4:
search()
elif ch==5:
display()
elif ch==6:
exit()
else:
print("You have entered invalid option")
menu()