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

Interface Python With MySQL1

Uploaded by

Nirmal Pal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
89 views12 pages

Interface Python With MySQL1

Uploaded by

Nirmal Pal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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 [Link]

Steps for connecting python program with MySQL

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


2. Import the package required ([Link] package)

[Link]
Or
[Link] as c

Here “c” is an alias, so every time we can use “c” in place of “[Link]”

3. Open the connection to MySQL database


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

<conn-object>=[Link](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 [Link]:

con =[Link]. 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=[Link]()

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


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

[Link](“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 [Link] no more
records left to fetch, it returns an empty list.
data= [Link]()

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= [Link]()

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 [Link] it will work
as fetchone() function.
It no more records left to fetch, it will return an empty list.
data= [Link]()

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


count = [Link]()
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()
[Link]()
# To check whether the connection to database is created or not

import [Link]
con=[Link](host='localhost',
user='root',
password='12345',
database='db')
if con.is_connected():
print("Successfully connected")

# To create table
import [Link]
con=[Link](host='localhost',
user='root',
password='12345',
database='mydb')
cursor=[Link]()
[Link](“create table emp(Eid int, Ename varchar(20),salary float(7,2))”)
print(“Table created”)
# To Describe table Structure
import [Link]
con=[Link](host='localhost',
user='root',
password='12345',
database='mydb')
cursor=[Link]()
[Link](“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)
[Link]()
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 [Link]
con=[Link](host='localhost',
user='root',
password='12345',
database='mydb')
cursor=[Link]()
while True:
Eid=int(input("Enter id"))
Ename=input("Enter name")
Salary=float(input("Enter marks"))
[Link]("insert into emp values({ },'{ }',{ })".format(Eid,Ename,Salary))
[Link]()
ch=input("Do you want to add more records?(Y/N):")
if ch in 'Nn':
break
print("Record Inserted")
Note:
New style
[Link]("insert into emp values({ },'{ }',{ })".format(Eid,Ename,Salary))
Statement can be written in Old style
[Link]("insert into emp values(%s,%s,%s)"%(Eid,Ename,Salary))

#To update record


import [Link]
con=[Link](host='localhost',
user='root',
password='12345',
database='mydb')
cursor=[Link]()
[Link]("update emp set Ename='Mudita' where Eid=14")
[Link]()
print("data updated")

Updating record (taking input from user.)


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

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

# To display all records


import [Link]
con=[Link](host='localhost',
user='root',
password='12345',
database='mydb')
cursor=[Link]()
[Link]("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 [Link]
con=[Link](host='localhost',
user='root',
password='12345',
database='mydb')
cursor=[Link]()
[Link]("select * from emp")
data=[Link]()
print(data)
data=[Link]() #repeat same cmd will return empty list
print(data)
print([Link])

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=[Link]()
print(data)

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


record

import [Link]
con=[Link](host='localhost',
user='root',
password='12345',
database='mydb')

cursor=[Link]()
[Link]("select * from emp")
data=[Link]()
print(data)
count=[Link]
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 [Link]
con=[Link](host='localhost',
user='root',
password='12345',
database='mydb')
cursor=[Link]()
[Link]("select * from emp")
data=[Link](3)
count=[Link]
print("Total number of rows retrieved in resultset:",count)
for row in data:
print(row)

Ex:
import [Link]
con=[Link](host='localhost',
user='root',
password='12345',
database='mydb')

cursor=[Link]()
[Link]("select * from emp")
data=[Link](2)
data=[Link]()
data=[Link]()
print(data)
count=[Link]
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 [Link]
con=[Link](host='localhost',
user='root',
password='12345',
database='mydb')

cursor=[Link]()
[Link]("select * from emp where Salary=34000")
data=[Link]()
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 [Link]
con=[Link](host='localhost',
user='root',
password='12345',
database='db')
cursor=[Link]()
rno=int(input(“Enter student rollno to search “)
[Link]("select * from class12 where Rollno=" +str(rno)
data=[Link]()
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 [Link]
con=[Link](host='localhost',
user='root',
password='12345',
database='db')
cursor=[Link]()
rno=int(input(“Enter student rollno to search “)
[Link]("select * from class12 where Rollno=%s”,(rno,))
data=[Link]()
if data!= None:
print(data)
else:
print(“No such rollno exist”)

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


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

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

import [Link]
con=[Link](host='localhost',
user='root',
password='12345',
database='db')
cursor=[Link]()
[Link]("select * from class12 where Gender=’%s’ " %(‘F ’))
data=[Link]()
for row in data:
print(row)

We can also take ‘Gender’ as input from user

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

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

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

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

You might also like