Interface Python With SQL
Interface Python With SQL
, 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