Interface python with MYSQL
Introduction
In order to create database connectivity, we need to create a database connectivity between
MYSQL and python we need to install MYSQL connector, MYSQL connector is used for
connecting python with MYSQL
MYSQL is used as backend
Connecting MYSQL and python
We go to python IDLE after installing mysql-connector
To check if MYSQL is connected properly
output
1
Create a curser query
A database cursor is a special control structure that facilitates the row by row processing of
records in the result set , i.e. set of records retrieved as per query
With the help of cursor object we execute the queries to retrieve the required data
Note that a database should be created in mysql before performing the queries
output
We can also use fetch function to extract the data
Output
2
We can also fetch data by stating conditions
Output
Extract data from the result set
1. Data=cur.fetchall() - to fetch all the data in the result set in the form of tuple as per query
2.Data=cur.fetchone() – to fetch one record from the result set , in first time it will fetch first
record , in second time it will fetch second record
3.Data = cur.fetchmany(n) – fetches n records from the table
4. variable = cursor.rowcount() – this property of cursor object return the number of row
retrieved
Outputs
3
Print("number of rows retrived is", cursor.rowcount())
4
Parameterized query
We use parameters to fetch the needed data from the given data
This can be done in 2 styles –
1. Old style
String template with % formatting
F%v
Where f is formatting string and v is the values to be formatted , v must be a tuple
Syntax example –“ select * from student where marks >%s” (%70,)
2.new style
String template with % formatting
Syntax example –
Str= select * from student where marks >{} and section = {},format (70,’b’)
We can also fetch data by entering the parameters using the input function
5
6
Retrieving data by new style formatting and input function
Commit() function
Commit() function is used to save the changes in a database physically
After performing queries like insert , update and delete queries , call commit function with
the help of connection object
For this first we need to create a new table then perform the queries and then call the
commit function
We can also check the creation of table simultaneously
7
Now we will insert data in table
We can check the inserted data in mysql
We can use loop to insert multiple data at once
8
We can check inserted values in mysql table
9
Now we will update the table
Note that to update the table in mysql we have to call commit function
This is the updated table after the update query
Now we will use delete query to dele a data in the table
10
Comparing it with original data we can see the data is successfully deleted in python as
mysql
11
QUESTIONS & ANSWERS
1. What is database connectivity?
Solution. Database connectivity refers to connection and communication between an
application and a database system.
2. What is Connection? What is its role?
Solution. A Connection (represented through a connection object) is the session between the
application program and the database. To do anything with database, one must have a
connection object.
3. What is a result set?
Solution. A result set refers to a logical set of records that are fetched from the database by
executing a query and made available to the application-program.
4. Which package must be imported in Python to create a database connectivity application?
Solution. There are multiple packages available through which database connectivity
applications can be created in Python. One such package is mysql.connector.
5. What will be the generated query string?
query = "INSERT INTO books(title, isbn) VALUES (%s, %s)".% ('Ushakaal',
'12678987036')
Solution. "INSERT INTO books (title, isbn) VALUES ('Ushakaal', '12678987836')"
6. Which record will get inserted in the table by following code?
import mysql.connector as sqltor
mycon = sqltor.connect(host = "localhost", user = "learner", passwd= "fast", database="test")
cursor mycon.cursor()
query = "INSERT INTO books(title, isbn) VALUES (%s, %s)".% ("Ushakaal',
'12678987036')
cursor.execute(query)
mycon.commit()
Solution. 'Ushakaal' ,12678987036
7. What will be the generated query string?
query= "INSERT INTO books (title, isbn) VALUES ('{}', {})". format('Ushakiran',
'42568987036')
Solution. INSERT INTO books(title, isbn) VALUES(('Ushakiran', '42568987036')"
12
8. Which record will get inserted in the table by the following code
import mysql.connector as sqltor
mycon = sqltor.connect(host = "localhost" , user = "learner" , passwd = "fast", database =
"test")
cursor = mycon.cursor()
query = "INSERT INTO books(title, isbn) VALUES('{}' , {})" , format( ' Ushakiran' ,
'42568987036' )
cursor.execute(query)
mycon.commit()
Solution. 'Ushakiran', 42568987036
9. Write a python database connectivity script that deletes records from catagory table of
database items that have name = 'Stockable'
Solution. import mysql.connector as ctor
dbcon = ctor.connect(host = "localhost", user = "learner" , passwd = "fast" , database =
"items")
cursor = dbcon.cursor()
sql1 = "DELETE FROM catagory WHERE name= '%s' "
data1 = ('Stockable',)
cursor.execute(sql1, data1)
dbcon.commit() #commit then changes
print("Rows affected: ", cursor.rowcount)
dbcon.close()
10. Explain the following 'results' retrieval methods with examples.
A. fetchone ()
B. rowcount ()
C. fetchall ()
Solution. (A) fetchone() :- The fetchone() method will return only one row from the result set
in the form of tuple containing a record.
(B) rowcount() :- cursor.rowcount() that always return how many records have been
retrieved so for using any of the fetch..() methods
(C) fetchall() :- The fetchall() method return all the rows from the result set in the form of a
tuple congaing the records.
For example.
11. What is the significance of using connect ()?
Solution. connect() function is used to connect or establish a connection with MySQL
database
12. The books table of test database contains the records shown below:-
13
Title ISBN
Die to Live 78127873915
Again? 23686286243
Ushakaal 12678987036
Ushakiran 42568987036
What will be the output produced by following code:
Solution. (Die to Live 78127873915)
(Again? 23686286243)
(Ushakaal 12678987036)
(ushakiran 42568987036)
14