0% found this document useful (0 votes)
20 views12 pages

Interface Python with MySQL1

Uploaded by

Nirmal Pal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
20 views12 pages

Interface Python with MySQL1

Uploaded by

Nirmal Pal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 12

Interface Python with MySQL

Every application requires data to be stored for future reference to manipulate


data. Today, every application stores data in a database for this purpose.
Examples:

 Reservation systems store passenger details for reserving seats and later for
sendingmessages or printing tickets.
 In schools, student details are saved for various purposes like attendance,
fee collections, exams, and report cards.

Python allows us to connect with all types of databases, including Oracle, SQL
Server, and MySQL.

To build a bridge to connect Python and MySQL, so that data can travel both
ways, we need a connector called mysql.connector

Steps for connecting python program with MySQL

1. Open python(start python editor to write script/code)


2. Import the package required (ie.mysql.connector package)

importmysql.connector
Or
importmysql.connector as c

Here “c” is an alias, so every time we can use “c” in place of “mysql.connector”

3. Open the connection to MySQL database


To create connection, connect() function is used
Its syntax is:

<conn-object>=mysql.connector.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.Eg:

con =mysql.connector. connect (host='localhost',

user='root',

password='12345',

database='db'

4. Create a cursor instance


A database cursor is a special control structure that facilitates the row by
row processing of records in the resultset (set of records retrieved as per
query).
Cursor stores all the data as a temporary container of returned data and we
can fetch data one row at a time from Cursor.

<cursor_obj>= <connection_obj>.cursor()
Eg:
cursor=con.cursor()

5. Execute the query and store it in resultset(using execute( ))


<cursor_obj> .execute(<sql query string>)
Eg:

cursor.execute(“select * from data”)

Note: Result set refers to a logical set of records that are fetched from the
database by executing an SQL query and made available to the application
program.

6. Fetch(Extract) data from resultset


To extract data from cursor following functions are used:
1. fetchall() : it will return all the record in the form of tuple.If no more
records left to fetch, it returns an empty list.
data= cursor.fetchall()

2. 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
data= cursor.fetchone()

3. fetchmany(n) : it will return n number of records in a form of list of tuple.


If no argument is specified,it will retrieve one record only.Then it will work
as fetchone() function.
It no more records left to fetch, it will return an empty list.
data= cursor.fetchmany()

4. rowcount :This property of a cursor return number of rows retrieved so far.


count = cursor.rowcount()
7. Clean up the environment
It ensures closing database connections, cursors, and freeing up any locks or memory
that may have been held during the operations.
<connection_object>.close()
Con.close()
# To check whether the connection to database is created or not

import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
password='12345',
database='db')
if con.is_connected():
print("Successfully connected")

# To create table
import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
password='12345',
database='mydb')
cursor=con.cursor()
cursor.execute(“create table emp(Eid int, Ename varchar(20),salary float(7,2))”)
print(“Table created”)
# To Describe table Structure
import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
password='12345',
database='mydb')
cursor=con.cursor()
cursor.execute(“desc emp”)
for i in cursor:
print(i)

Output:
('Eid', 'int', 'YES', '', None, '')
('Ename', 'varchar(20)', 'YES', '', None, '')
('salary', 'float(7,2)', 'YES', '', None, '')

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 con)
con.commit()
Commit() function is used to save the changes in a database physically.
After performing :insert,update and delete queries, call the commit() function
with the help of an connection object.

# To insert data into table(taking input from user)


import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
password='12345',
database='mydb')
cursor=con.cursor()
while True:
Eid=int(input("Enter id"))
Ename=input("Enter name")
Salary=float(input("Enter marks"))
cursor.execute("insert into emp values({ },'{ }',{ })".format(Eid,Ename,Salary))
con.commit()
ch=input("Do you want to add more records?(Y/N):")
if ch in 'Nn':
break
print("Record Inserted")
Note:
New style
cursor.execute("insert into emp values({ },'{ }',{ })".format(Eid,Ename,Salary))
Statement can be written in Old style
cursor.execute("insert into emp values(%s,%s,%s)"%(Eid,Ename,Salary))

#To update record


import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
password='12345',
database='mydb')
cursor=con.cursor()
cursor.execute("update emp set Ename='Mudita' where Eid=14")
con.commit()
print("data updated")

Updating record (taking input from user.)


import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
password='12345',
database='mydb')
cursor=con.cursor()
Eid=int(input("Enter eid for updation"))
Ename=input("Enter new name")
cursor.execute("update emp set Ename='{ }' where Eid={ }".format(Ename,Eid))
con.commit()
print("data updated")
We can also write with old style
cursor.execute("update emp set Ename='%s' where Eid=%s"%(Ename,Eid))

# To delete record
import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
password='12345',
database='mydb')
cursor=con.cursor()
Eid=int(input("Enter eid to delete"))
cursor.execute("Delete from emp where Eid={ }".format(Eid))
con.commit()
print("Record deleted")

# To display all records


import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
password='12345',
database='mydb')
cursor=con.cursor()
cursor.execute("Select * from emp")
for i in cursor:
print(i)

Output:

(11, 'minakshi', 50000.0)


(13, 'rakesh', 34000.0)
(14, 'Mudita', 67000.0)
(16, 'mohit', 58000.0)
(17, 'Anika', 78000.0)

#Using fetchall() function :extracting all records in the form of list of tuples.
import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
password='12345',
database='mydb')
cursor=con.cursor()
cursor.execute("select * from emp")
data=cursor.fetchall()
print(data)
data=cursor.fetchall() #repeat same cmd will return empty list
print(data)
print(cursor.rowcount)

Output:

[(11, 'minakshi', 50000.0), (13, 'rakesh', 34000.0), (14, 'Mudita', 67000.0),


(16, 'mohit', 58000.0), (17, 'Anika', 78000.0)]
5
If you use below statement twice, it will return empty set
data=cursor.fetchall()
print(data)

# Using fetchone() function :extracting single record o none if there is no more


record

import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
password='12345',
database='mydb')

cursor=con.cursor()
cursor.execute("select * from emp")
data=cursor.fetchone()
print(data)
count=cursor.rowcount
print("Total number of rows retrieved in resultset:",count)

output:

(11, 'minakshi', 50000.0)


Total number of rows retrieved in resultset: 1

#using fetchmany(size)
import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
password='12345',
database='mydb')
cursor=con.cursor()
cursor.execute("select * from emp")
data=cursor.fetchmany(3)
count=cursor.rowcount
print("Total number of rows retrieved in resultset:",count)
for row in data:
print(row)

Ex:
import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
password='12345',
database='mydb')

cursor=con.cursor()
cursor.execute("select * from emp")
data=cursor.fetchmany(2)
data=cursor.fetchone()
data=cursor.fetchone()
print(data)
count=cursor.rowcount
print("Total number of rows retrieved in resultset:",count)

output:

(16, 'mohit', 58000.0)


Total number of rows retrieved in resultset: 4

We can use fetchall function to fetch records using where clause


import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
password='12345',
database='mydb')

cursor=con.cursor()
cursor.execute("select * from emp where Salary=34000")
data=cursor.fetchall()
for row in data:
print(row)

Output:

(13, 'rakesh', 34000.0)

Parameterized Query
We can pass values to query to perform dynamic search like we want to search for
any student rollnumber 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.
import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
password='12345',
database='db')
cursor=con.cursor()
rno=int(input(“Enter student rollno to search “)
cursor.execute("select * from class12 where Rollno=" +str(rno)
data=cursor.fetchone()
if data!= None:
print(data)
else:
print(“No such rollno exist”)

 Old style: String template with % formatting

f%v
where
f is a template string
v specifies the values to be formatted using the template.
“Select * from student where marks>%s” %(75,)
Ex1:
import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
password='12345',
database='db')
cursor=con.cursor()
rno=int(input(“Enter student rollno to search “)
cursor.execute("select * from class12 where Rollno=%s”,(rno,))
data=cursor.fetchone()
if data!= None:
print(data)
else:
print(“No such rollno exist”)

 New style: String template with {} and format function


Ex:
import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
password='12345',
database='db')
cursor=con.cursor()
name=input(“Enter student name: “)
cursor.execute("select * from class12 where Rollno={}”.format(rno)
data=cursor.fetchone()
if data!= None:
print(data)
else:
print(“No such rollno exist”)

Str=”Select * from student where Marks> { } and Gender=’ { }’”.format(75,’F ’)

import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
password='12345',
database='db')
cursor=con.cursor()
cursor.execute("select * from class12 where Gender=’%s’ " %(‘F ’))
data=cursor.fetchall()
for row in data:
print(row)

We can also take ‘Gender’ as input from user

import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
password='12345',
database='db')
cursor=con.cursor()
g=input(“Enter Gender: ”)
cursor.execute("select * from class12 where Gender=’%s’ " %(g))
data=cursor.fetchall()
for row in data:
print(row)

We can also take ‘Gender’ and ‘marks’ as input from user

import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
password='12345',
database='db')
cursor=con.cursor()
g=input(“Enter Gender: ”)
m=int(input(“Enter marks >: ”)
cursor.execute(“select * from class12 where Gender=’%s’ and
marks>%s” %(g,m))
data=cursor.fetchall()
for row in data:
print(row)

Or
Using new style{}
import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
password='12345',
database='db')
cursor=con.cursor()
g=input(“Enter Gender: ”)
m=int(input(“Enter marks >: ”)
cursor.execute(“select * from class12 where Gender=’{ }’ and marks>{ }”
.format(g,m))
data=cursor.fetchall()
for row in data:
print(row)

You might also like