I
Interface Python
with MySQL
gn ve Ort
15.1. Introduction
15.2. Connecting to MySQL from Python
15.3. Parameterised Queries
15.4 Performing INSERT and UPDATE Queries
15.1 INTRODUCTION
When you design real-life applications, you are bound to
vncounter situations wherein you need to manipulate data ines
" a
stored in a database through an application designed by You. gefore you start_warking_ with
Since you are developing Python applications in this chapter python mysal connector, you need
var discussion will be based on how you can connect to at install on your computer. Both
MySQL database from within a Python script. pip and Condsa installation of Python
MySQL connector is given in
In order to connect to a database from within Python, you Appendix € of this book. So, please
need a library that provides connectivity functionality. There refer, to Appendix E for the
are many different libraries available for Python to accomplish installation of the same.
this, We shall work with mysql connector library for the same.
15.2 CONNECTING TO MYSQL FROM PYTHON
After you have installed Python MySQL connector (as
: ! per Appendix E), i ion
Scripts using MySQL.connector library that can connect to MySQL ‘labees to a in
ym. withis
Python.
‘ager548
COMPUTER SCIENCE WITH PYTHON ~ ya,
15.2.1. Steps for Creating Database Connectivity Applications
‘There are mainly scvvit steps that must be followed in order to create a database connectivity
application.
Step1 Start Python.
Step 2 Import the packages required for database programming.
Step3 Open a connection to database.
Step 4 Create a cursor instance.
Step5 Execute a query.
Step 6 Extract data from result set.
Step7 Clean up the environment.
Let us talk about these steps in details.
Step 1. Start Python
Start Python's editor where you can create your Python scripts. It can be IDLE or Spyder IDE ~
whatever you feel comfortable in.
Step 2. Import mysql.connector Package
First of.all you need to import mysql.connector package in your Python scripts. For this, write
import command as shown below :
import mysql.connector
a a Yow can use any identifier of your choice
import mysql.connector as sqltor
Step 3. Open a Connection to MySQL Database
Next you need to establish connection to a MySQL database using connect ) function of
mysql.connector package.
The connect ) function of mysqL.connector establishes connection to a MySQL database and
requires four pardmeters, which are :
«Connect ion-Object> = mysql.connector.connect (host =
, user = s
passwd = [, database = name. You shall be using this name for
executing queries and for other tasks on connected database.
For example : loginid and password of your MySQL database
import mysql. connector as sqltor 7. \
The comenion > CON = sqltor.connect (host = "localhost", user = "root", passwd = "MyPass",
object
database = “test”)
ta MyS0L database
inalpier 15 INTERFACE PYTHON WITH mys
cho
549
since we imported mysql.connector package as sql
iS sqltor,
. j.connector. If "
mysq ‘you have imported the package as we are using the name sqltor in place of
import mysql. connector
‘then you need to write above function as :
con = mysql.
mye 'ysqi-connector.connect (host = "localhost", user = “root”
user = "root,
passwd = "MyPass", databas
test”)
‘The above command wi .
nso ommand will etablih conection to MySQL database with were “00”,
10 the MySQL database namely test which exists on the MySQL.
Here, you must ensure that the
for yout local MYSQL installation. and password that you specify are valid user and passion
If Python reports no error, it means you have successfully
connected to MySQL database. You can also check for database Connection Obie
successful connection using function is_connected( ) with controls the connection to the
connected object (which returns True, if connection is database. It represents @ unique
successful, i, if you may write following additional code to ren draenei
check if the connection is successful or not)
ames
cnt
The same connection object with which we
if mycon.is_connected(): connected to MySOL database
print (‘Successfully Connected to mySQL database”)
Following screenshot shows you the output produced by code shown below :
import mysql. connector as sqltor
mycon = sqltor.connect(host = "localhost", user = "root",
if mycon.is_connected():
print ( ‘Successfully Connect
passwd = "MyPass”, database ="test")
ted to MySQL database")
4 aie, Sea
sneer 5
Te Gar Surh_oace fam Dobos, Cone :
Rea.eo > Gee & mI
Se src
G| ein 8 |
import mysqi.connector as salton . , In [8]: runfile("€=/G onic Py
cart yaa conn past = ecelnost” ser = “Foot wee retep se Pye acfvon AIT Ne
ety saltor donnece( i Successfully Connected SQL database
34F aycon.is_connected() .
4 “print( ‘Successfully Connected 0 Mysql database")
Step 4. Create a Cursor Instance
control structure of database connectivity. Normally when you
A database cursor is useful ct
thin a script/program, then the query gets sent to the server,
connect to a database from wi . ;
of records retrieved as per query) is sent over
where it gets executed, ‘and the resultset (the
in one burst of activity ie, in one g0- But you may want to access the
the connection to you, c
retrieved data, one row ata time. But query processing cannot happen as one row ata time, s0 a
special type of control structure called database cursor can be created that gets the access of all
the records retrieved as per query (called the resultset) and allows you to traverse the resultset
row by row.550
Step
Step
COMPUTER SCIENCE WITH PYTHON ~ XiI
In this step(step 4), you create an instance of cursor by using EMeuiiniieetiotls
cursor( ) function as per following syntax : A Databave canoe 2 spc
control structure that facta
= .cursor() ie roe by row! procenine| of
That is, for our connection established in earlier steps, we can _records in the resultset, ie, the set
create cursor( ) by writing :
cursor = mycon.cursor()
Cure te created 7” Comecon objet
Since we established database connection through connection object mycon earlier, we have
created a cursor object using the same connection object mycon.
5. Execute SQL Query
Once you have created a cursor, you can execute SQL query using execute( ) function with
cursor object as per following syntax :
.execute()
For example, if you want to view alll the records of table data which is a table in the database
test to which you established connection in step 2, you can execute SQL query “select * from
data” by writing :
cursor. execute("select * from data”)
er soem ive S01 urn ate
The above code will execute the given SQL query and ia
]
store the retrieved records (i.e., the resultset) in the cursor ‘The result set refers to a logical set
of records that are fetched from
object (namely cursor) which you can then use in your |
rograms/scripts as required. the database by executing an SQL|
Ls 7 ae query and made available to the |
application program.
6. Extract Data from Resultset ——_—-
You will need this step (step 6) if you have retrieved records from the database using SQL
SELECT query and need to extract records from the retrieved resultset. Once the result of query
is available in the form of a resultset stored in a cursor object, you can extract data from the
resultset using any of the following fetch...() functions.
() = .fetchall( ). It will return all the records retrieved as per query ina
tuple form (ie., now will be a tuple.)
(ii) = .fetchone( ). It will return one record from the resultset as a tuple or
list. First time it will return the first record, next time it will fetch the next record and so
on.
This method returns one record as a tuple : if there are no more records then it returns
None.
= .fetchmany(). This method accepts number of records to fetch and
returns a tuple where each record itself is a tuple. If there are not more records then it
returns an empty tuple.
(iv) = .rowcount. The rowcount is a property of cursor object that
returns the number of rows retrieved from the cursor so far. Following examples will
make it more clear.
Git)r
: INTERFAC
cope 15 «INTERFACE PYTHON WITH MySQL 551
Let us now see with following code examy i
g ples how these functions work. For the following code
‘examples, we shall be connecting to database test, table student that has the following data init:
T ‘ble student of MySQL database test
Rollno Name Marks Grade | Section Project
3o1_| Ruhani_| 76.80 A ‘A__| Pending
102__| George | 71.20 B ‘A__| Submitted
103__| Simran 81.20 A B Evaluated
104 | Ali 61.20 B C__| Assigned
105 | Kushal_| 51.60 c C__| Evaluated
106__| Arsiya__| 91.60 AY B__ | Submitted
307_- | Raunak | 32.50 F B__| Submitted
Following code examples assume that the connection to the database has been established
using connect( ) method of mysgl.connector as discussed in earlier steps. That is, all the
-d for them :
following code examples of fetch functions have following code pre-executes
import mysql. connector as sqltor
mycon = sqltor. connect (host = "localhost", user = “root, passwd = "MyPass”»
database = "test")
4 mycon.is_connected() == False:
print( ‘Error connecting to MySQL database’) ye so1 queryremives al the daw of
cursor = mycon.cursor() table student of database test
execute("select * from student")
cursor.
to above code how all fetch..() methods will behave.
Let us now see that in addition
(i) The fetchall( ) method
The fetchall( ) method will
containing the records.
# database connected es}
Se cursor. fetchall() +————— Fetch all she records inthe resultset
‘The data varable will *” count = cursor .rowcount <———_ How many records returned by SQL query in the resultset
Store the reieved we oe :
records from the
resist in the form of
tuple (a tuple of re-
return all the rows from the resultset in the form of 2 tuple
‘tablished and cursor object created
>
print( "Total number of rows retrieved in resultset :", count)
“1
for row in data! <——— Now you ean process the data tuple
print (row) ‘one row ata time
‘The output produced by above code is:
rows retrieved in resultset : 7 #————— Result of eu
pecimal(‘76.80"), ‘A’, A", ‘Pending’)
pecinal('71.20"), ‘B', ‘A’, ‘submitted’
(403, ‘simran’, Decimal ('81-20"), "A's ‘e’, ‘evaluated’
Goa, tari", decimal (*62-20"), 'B', °C tassigned’) | *—— cursorfetchall)'s result
Gos, ‘Kushal’, decimal ¢'52-60'), "C', *C' ‘evaluated’) was stored in data, which is
(106, ‘Arsiya’, pecimal(‘91.60"), ‘At’, "B’, submitted’) ‘then printed row by row
(207, ‘Raunaq’, decimal (‘32-50"), ‘F's “Bly submitted’)
Total number of roe ore
01, ‘Ruhan’
02, ‘George’,
Sapa
ma552 COMPUTER SCIENCE WITH PYTHON ~ Xi!
(i) The fetchmany( } method
‘The fetchmany() method will return only the number of rows from the resultset in the
form of a tuple containing the records.
: #database connected established and cursor object created
> data = cursor. fetchmany (4) Feel 4 records in the resultset
The data variable will o*"
store the rived r-—f—-count
cond from the resuliset .
in the form ofa tuple
(a.ple of rors),
‘ursor..rowcount <———— How many records returned by SQL query in the resultset
pi =,
print("Total number of rows retrieved fromresultset :", count)
“*
for row in data : <——— ow you can process the data tuple
print(row) one row at a time
‘The output produced by above code is :
Total number of rows retrieved from resultset : 4 <—— Resul of cursor roweount
(101, ‘Ruhani’, Decimal(‘76.80"), ‘A’, ‘A’, ‘Pending") ia
02, ‘George’, Decimal(‘71.20"), ‘8’, ‘A’, ‘Submitted’
(203, ‘Simran’, Decimal(‘81.20"), ‘A’, ‘B’, ‘Evaluated’) The qursorroweount retums how many
(04, ‘ATi", — Decimal(‘61.20"), ‘B’, ‘C’, ‘Assigned’) ——_rowshave been so farretrieved through
fetch..( ) methods from the cursor.
(iii) The fetchone( ) method
The fetchone( ) method will return only one row from the resultset in the form of a tuple
containing a record. A pointer is initialized which points to the first record of the resultset as
soon as you execute a query. The fetchone( ) returns the record pointed to by this pointer. When
you fetch one record, the pointer moves to next record of the recordset. So next time , if you
execute the fetchone( ) metod, it will return only one record pointed to by the pointer and after
fetching, the pointer will move to the next record of the resultset.
‘Also, carefully notice the behaviour of cursor.rowcount that always returns how many records
have been retrieved so far using any of the fetch..( ) methods.
1 #database connected established and cursor object created
data = cursor.fetchone() <—__paich records inthe resulet
count = cursor. rowcount (first time, only the first record is retrieved)
print("Total number of rows retrieved from resultset :*,*count)
print (data)
print("\nAgain fetching one record")
data = cursor.fetchone() <———_____ ex ferchone() will fetch the next record
count = cursor. rowcount from the resulset
print (“Total number of rows retrieved from resultset
print(data)
Result of cursor.rowcount
Total number of rows retrieved in resultset : 14———— This time itis 1 because fetchone() method
01, ‘Ruhani", Decimal(‘76.80"), ‘A’, ‘A', ‘Pending?) "revel only I record from the cursor
Again fetching one record Result of cursor.rowcount
Total number of rows retrieved from resultset : 2<——— This imei is 2 because ftchone()
G02, ‘George’, decimal(‘71.20’), ‘B’, ‘A’, ‘Submitted” soaead retired cely 1 record (eat
9 imal ¢ > uber teed’) record) from the cursor but SO FAR
2 records have been retrieved.
*eount)v
coo 15 INTERFACE PYTHON WITH MySQL 553
Now can you guess the output of following code?
import mysql.connector as sqltor
mycon = sqltor.connect(host = " “
(host = "localhost", user = "root", passwd = "MyPass”»
| database ="test")
if mycon. is_connected() == Falsi
print( ‘Error connecting to MySQL database’ )
j cursor = mycon.cursor()
cursor.execute("select * from student")
data = cursor. fetchone()
count = cursor. rowcount
print ("Total number of rows retrieved so far from resultset :", count)
data = cursor.fetchone()
count = cursor.rowcount
print(“Total number of rows retrieved so far from resultset :", count)
data = cursor. fetchmany(3)
count = cursor.rowcount
print(“Total number of rows retrieved so far from resultset
:", count)
Well, you guessed it right. The output is :
Total number of rows retrieved so far from resultset : 1
Total number of rows retrieved so far from resultset :
sta] number of rows retrieved so far from resultset : 5
Step 7. Clean Up the Environment
through all the processing, in this final step, you need to close the connection
After you are
established.
This, you can do as follows :
‘econnection object>.close( )
eg., we established the database connection vi
We shall write =
mycon.close( )
‘a connection object mycon above, so
fete code wherein only first three records of the database table
Following example lists the compl
harps re listed row by row.
student of MySQL database test 2
15.1. write a Python program that displays first three rows fetched from student table of MySQL database
“es
ind password is “fast”)
(Note. user is “learner” a
connector as sqltor
‘connect (host = "localhost", user =
ted() == False:
connecting to MySQL database’ )
import mysql.
mycon = sqitor-
if mycon. is_connect
print (‘Error
“Learner, passwd = "fast", database = "test")554 COMPUTER SCIENCE WITH PYTHON ~ XI
cursor = mycon.cursor()
cursor.execute("select * from student")
data = cursor. fetchmany(3)
count = cursor.rowcount
for row in data : lo1, ‘Ruhani’, Decimal('76.80"), ‘A’, ‘A’, ‘Pending’)
print(row) (102, ‘George’, Decimal(‘71.20"), ‘B’, ‘A’, ‘Submitted’)
mycon.close() (203, ‘Simran’, Decimal(‘81.20'), ‘A’, ‘B’, ‘Evaluated’)
15.3. PARAMETERISED QUERIES
In previous section, you learnt about how you can execute simple SQL queries after establishing,
connection to MySQL database. But SQL queries that were used, were simple queries.
Sometimes, you may need to run queries which are based on some parameters or values that
you provide from outside, e.g.,
ae
SELECT * FROM student WHERE MARKS > inp ;
Such queries are called parameterised queries. To execute parameterised queries in a
mysql.connector connection, you need to form SQL query strings that include values of
parameters. Let us talk about how you can form such query strings.
Forming Query Strings
Note, for all the following code examples, we are again connecting to the student table of
MySQL database test, the one we have used earlier. The connection object name is mycon and
the cursor object name is cursor as earlier. That is, the code for connection is :
import mysql. connector as sqltor
ycon = sqltor.connect(host = “localhost, user = "learner", passud
if mycon.is_connected() == False:
print (‘Error connecting to MySQL database’ )
cursor = mycon.cursor()
Let us now discuss about how you can form parametrised query strings. To form query strings
based on some parameters, you can go for one of the following two methods:
(i) Old Style : String Templates with % formatting
In this style, string formatting uses this general form: %
fast", database = "test")
where f is a template string and v specifies the value or values to be formatted using that
template. If multiple values are to be formatted, v must be a tuple, For this you can write the
SQL query in a string but use a %s code in place of the value to be provided as a parameter.
For example,
"select * from student where marks > Xs" q————~ This means itis a parameter and its
value must be provided
The above string is an incomplete string (only f, no %v here) as it contains a placeholder for
Parameter as Yo, but its parameter value is not provided here. To complete it, you
‘must provide a tuple of values with% prefixed to it next tothe string (called the value tuple, % v),y
copter 15 INTERFACE PYTHON WITH MSc .
555
eg, ifyou want to provide v
fee pk aa loa alue 70 for %s placeholder in above query string, you can form the
(78,) <—— For single vate tobe stored t tuple fol
2 comma must follow it
Now you can complete the above SQL query string as follows :
select * from student where marks >%s" %(70,)
ee
z
Now you can store this query stri i
Pace crectbet)etied a me lean variable and then execute that variable through
td
’ atabase connected established and cursor object created
select * from student where marks > %s" %(7®, )
st
aie
cursor .execute( st ) hh
data = cursor. fetchall()
for row in data: Do not forget to enclose placeholder
‘%s in quotes for string parameters in
string template.
print (row)
(ol, *puhani’, Decimal(‘76.80"), ‘A’ “at, ‘Pending’)
(102, ‘George’, Decimal(‘71.20'), ‘B's ‘A’s ‘submitted’ )
(203, ‘Simran’, Decimal(‘81.20"), ‘A’, ‘B’s “evaluated’)
(06, ‘Arsiya’, Decimal(‘91.60"), ‘At’, ‘B's “ submitted’)
multiple parameter values, but one caution you must
In the similar manner, you may add
Jaceholder %s in quotes for string parameters ¢8.-
exercise is that do not forget to enclose p
# database connected established and cursor object created See, “és enclosed in
(quotes for string value
st = “select * from student where marks > %5 and section = '%s'" % (72, °B')
sexecute(st, V tuple containing a number
cursor execute(st) vanes
data = cursor. fetchall()
for row in data = earn hen
‘i (203, ‘simran’, Decimal('81.20'), A", *, ‘evaluated”
nt (row)
prtanoas) (406, ‘arsiya’, Decimal(‘91.60"), tae!, ‘B", ‘Submitted”)
‘Altematively, you can provide the tuple with the execute( ) function as :
eterised sql query string>, )
cursor -execute( 7@ and section = ‘B' “ orang lon
And it will yield the same query result as earlier.y
coe"
jer 15+ INTERFACE PYTHON WITH MySat
557
Common Cursor Methods
execute(operation |, params) ~ Executes an SOL stat
fatement.
fetchone( ) ~ Fetches th
fetchall()~ Fetches re sas Tow as a sequence ; returns None when no more data
‘emaining rows, current pointer position onwards
fetchmany((size = cu is
sorartaysize]) ~ Fetches the next set of rows as a sequence of
uences (default is set usin,
ou Ea
rows to fetch. 18 Cursor.arraysize); returns an empty sequence when no more
154 PERFORMING INSERT AND UPDATE QUERIES
IN
ae and UPDATE ar also SQL commands, you can execute them st the way you
e queries earlier. That is, store the query ina string as a simple query OE 2S:
a parameterised query and execute it using cursor.execute( ) method.
BUT one important thing you must ensure with INSERT and UPDATE queries (which make
changes to the database unlike SELECT) you must commit your query after executing INSERT
and UPDATE queries. For this your must run commit() method of connection in the end ie.
.commit( )
This is done to reflect the change in the database physically.
Consider following examples (assuming that connection has been established with student table
of test database as earlier; the connection object is mycon and the cursor object name is cursor)
()) INSERT query example
st = "INSERT INTO student(rollno, name, marks, grade, section)
VALUES({}» "C's Oh» “CO's (2) -Format(40e, "Eka", 84.2, "A's 8’)
cursor.execute(st)
mycon.commit()
JLECT query to check if your data has been
You can run a SEI added to the table or not.
(i) UPDATE query example
‘UPDATE student SET marks = {}
st
st
Noe ts WHERE marks = {}"-format (77, 76-8)
cursor.execute(st)
1. How is database connectivity useful ? mycon.commit ()
2. What is a connection ? ;
3. What is a result set ? In the same manner, you can also run DELETE queries, but
4c whatts the package sed for ceming », DONOT fOrge4t0 commit() after running the query. (Refer
Python database com to solved problem 10 that executes a DELETE query)
application. With this we have na
‘you use for
which farction/method do you 88 BT come to the end of his
establishing connection fa, _chapter. Let us quickly Please note, you need to run commit()
Which function/method do you ust revise that we have with connection object for queries
executing an SOL query ? that change the data of the database
Which method do you use to fetch Jeamt 20 far. table so that changes are reflected in
‘the database.
records from the resultset ?COMPUTER SCIENCE WITH PYTHON ~ xi
LET Us REVISE
—
To connect to a database from within a programming application, you need a framework that facilitates
‘communication between two different generes of software (programming application and DEMS)
% To connect from Python to MySQL, you need a library called mysql connector.
%& You muse import mysql.connector in the Python progranvscript before writing code for connectivity.
&% Steps t0 create a database connectivity Python application are :
Step 1 Start Python. Step 2 Import the packages required for database programming.
‘Step 3 Open a connection, Step 4_Create a cursor instance.
Step 5 Execute a query, Step 6 Extract data from result se
A database Connection object controls the connection to the database. It represents a unique session with a
database connected from within a script/program.
A Database Cursor is a special control structure that facilitates the row by row processing of records in the
resultset, ie., the set of records retrieved as per query.
The 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.
‘You can use connect() method for establishing database connection, cursor( ) to create a cursor and execute() to
execute an SQL query.
To fetch records from a result set, you can use fetchone( ), fetchmany( ) and fetchall() methods.
‘For INSERT, UPDATE and DELETE queries, you must run commit( ) with the connection object.
%
‘Step 7 Clean up the environment,
Opriective Type Questions
OTQs
Multiple Choice Questions
1. In order to open a connection with MySQL database from within Python using mysql.connector
package, function is used.
(2) open( ) (®) database( )
controls the connection to an actual database, estabilised from within a Python
(© connect( ) (c) connectdb( )
2. A database
program.
(@) database object (®) connection object
(0 fetch object (0) query object
The set of records retrieved after executing an SQL query over an established database connection
is called 2
(@) table (®) sqlresult
A database is a special control structure that facilitates the row bj
records in the resultset.
(a) fetch
5. Which of the following is not a legal method for fetching records from database from within
(6) result (©) resultset
Y TOW processing of
() table (©) cursor (©) query
Python?
(a) fetchone( ) (b) fetchtwo( ) (c) fetchall( ) (d) fetchmany( )por 15 INTERFACE PYTHON WITH Myscu.
fo obtain all the records retrieved,
. 1 You may use . hod.
; a a () fetchone( ) (6 fetchtuplet ) aaa ot these
5g fetch) Pie records from the resultset, you may use , niethod.
y() ——_(c) fetchmulti
o, Torun an SQL query from within Python, you may ee ate © ear )
___ method( )
, Oe changes ee ) (@mun() (@ all of these
: ;
0 Tot le in the database permanently, you need to run .
(a) done( ) (b) reflect( ) (0 commit( (© final)
fil in the Blanks
1. A database controls the connection to the database. It represents a unique session
with a database connected from within a script/program.
A is a special control structure that facilitates the row by row processing of records
in the resultset, ie., the set of records retrieved as per query.
3, The 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.
is established using connect( ).
is created so that the sql query may be
4, After importing mysql.connector, first of all
5, After establishing database connection, database ___
executed through it to obtain resultset.
6, The _____ returns how many rows have been fetches
of sql query through database cursor results into al th
d to far using various fetch methods.
7. The running records returned in the form
of
True/False Questions
1. With creation of a database connection obj
database starts.
2. The sql query upon execution via establis
chunks.
3, The cursor.rowcount gives the count of
4, The cursor.rowcount returns how many rows
from the cursor.
5. ADELETE or UPDATE or INSERT query requires commit() to reflect the changes in the database.
nat the énd of the book.
ject from within a Python program, a unique session with
shed database connection returns the result in multiple
records in the resultset.
have been so far retrieved through fetch.,() methods
NOTE ; Answers for OTQs are give!
Solved Problems
1. What is database connectivity ?
Solution. Database connectivity Te
and a database system
fers to connection and communication between an application560
COMPUTER SCIENCE WITH PYTHON ~ xi)
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.
What is a result set ?
Solution, A result set refers to a logical set of records that are fetched
executing a query and made available to the application-program.
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.
What will be the generated query string ?
query = “INSERT INTO books(title, isbn) VALUES(%s, %s)".% ( ‘Ushakaal’ ,'12678987036')
from the database by
Solution. "INSERT INTO books(title, isbn) VALUES( ‘Ushakaal' , '12678987036" )”
Which record will get inserted in the table by following code?
import mysql.connector as sqltor
rycon = 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. conmit()
Solution, 'Ushakaal' 12678987036
What will be the generated query string ?
"INSERT INTO books (title, isbn) VALUES(‘{}', (3)
Format( ‘Ushakiran’ , '42568987036")
que
Solution. “INSERT INTO books(title, isbn) VALUES((‘Ushakiran’ , *42568987636" )"
Which record will get inserted in the table by following code
import mysql.connector as sqltor
ycon = 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
The books table of test database contains the records shown below.
Title ISBN
Die to Live 78127873915
Again? 23686286243
Ushakaal 12678987036
Ushakiran’ 42568987036je 15+ INTERFACE PYTHON WITH mys
561
what wil Be the output produced by fot
import mysql.connector as ation’ oe
conn = sqltor.connect(host = "localhost"
cursor = conn. cursor()
cursor.execute( "SELECT *
swe cursor.fetchone() eat”)
while row is not None:
print(row)
row = cursor. fetchone()
» user =" "
ser = "learner", passwd » “fast, database ="test”)
solution.
i (ie to Live 78127873915)
(Again? 23686286243)
| (ushakaal 12678987036)
i (Ushakiran 42568987036)
10. ages ee connectivity script that deletes records from category table of database items that
i solution.
import mysql.connector as ctor
docon = ctor.connect (host = "localhost", user = "learner", passwd = "fast",
database = "items")
cursor = dbcon. cursor()
sqll= ‘DELETE FROM category WHERE name= ‘%s'"
datat = ('Stockable' ,)
cursor.execute(sql1, datat)
dbcon.conmit() # commit the changes
print ("Rows affected: ", cursor. rowcount)
dbcon.close()
GLOSSARY
a
Connection Session between the oP}
esuit Set A logical set of records fetched from dotabase bose
Assignment
ons/Conceptval Questions
from with Java application ?
namely School and then fetch all those records from table
lication program and the databose.
.d on query and made available to the application.
Type A: Short Answer Quest
1. What are the steps to connect to
2. Write code to connect to a MySQL database
Student where grade is ‘A’
3. Predict the output of the following code :
import mysql.connector
db = mysql.connector .conn
a database
ect (--)COMPUTER SCIENCE WITH PYTHON ~ xi
cursor = db.cursor()
sqli = “update category set name= "Xs" WHERE ID= Xs" % (‘CSS',2)
cursor. execute(sql1)
db.commit()
print ("Rows affected:", cursor.rowcount)
db,close()
4. Explain what the following query will do?
import mysql. connector
db = mysql. connector. connect (..--)
cursor = db. cursor()
person_id = input("Enter required person id")
lastname = input("Enter required lastnane")
db.execute("INSERT INTO staff (person_id, lastname) VALUES ({}, ‘{}') "+
format(person_id, lastname)
db, comnit()
db. close()
5. Explain what the following query will do?
import mysql. connector
db = mysql.connector.connect(.~)
cursor = db. cursor()
db.execute("SELECT * FROM staff WHERE person_id in {}".format ((1,3,4)))
db. commit()
db.close()
Type B : Application Based Questions
1. Design a Python application that fetches all the records from Pet table of menagerie database.
2. Design a Python application that fetches only those records from Event table of menagerie database
where type is Kennel.
3. Design a Python application to obtain a search criteria from user and then fetch records based on that
from empl table. (given in chapter 12)ANSWER KEY
CHAPTER 15 : INTERFACE PYTHON WITH MySQL
Multiple Choice Questions
L© 2 ©
7. @) 8. (&)
Fill in the Blanks
1. connection object
4. database connection
True/False Questions
LT 25
3. (d) 4, (c) 5. (b) 6 (0)
9. (b) 10. (c)
2. Database cursor 3. resultset
5. cursor 6. cursor.row count 7. resultset
3. F 4. T 5. T