Interface Python
with SOL
8.1 INTRODUCTION
patabases play a vital role in the efficient working of an organization. From a construction firm to
a stock exchange, every organization depends on large databases. ‘These are essentially collections
oftables ‘and are connected with each other through fields or, more precisely, columns/attributes.
these database systems support SQL (Structured Query Language), which is used to access data
and also to create and exploit the relationship between stored data. Additionally, these databases
gupport database normalization rules for avoiding redundancy of data. Python programming
ranguage has powerful features for database programming. Python supports various databases
like MySQL, Oracle, Sybase, PostgreSQL, etc. It also supports Data Definition Language (DDL),
Data Manipulation Language (DML) and Data Query Statements. But Python standard library
does not come with an RDBMS interface, For database programming, the Python DB-API is a
widely-used module that provides a Database Application Programming Interface. It is 2
standard for database interfaces. Database Application Programming Interface is
a set of tools
tised by an Application program to communica’ ‘with the Operating System or other programs
juch as Database Management System. These ‘APIs are implemented by calling fu!
nctions in the
programs which provide linkage to the required program to perform a task.
interfaces adhere to this standard.
Most Python database i
n Database API supports a wide range
We can choose the right database for our application. Pytho
of database servers such as—
+ GadFly
+ mSQL
« MySQL
+ PostgreSQL
+ Microsoft SQL Server 2000
+ Informix
+ Interbase
+ Oracle
+ Sybase8.1
INTRODUCTION
Interface Python
with SQL
ases play a vital role cic -,
Databases play in the efficient working of an organization. From a construction firm to
ast
cock eX
change, every organizati
[bles and are eee nization depends on large databases. These are essentially collections
a with each other through fields or, more precisely, columns/attributes.
‘These database systems support SQL (Structured Query Language), which is used to access data
and
support datab:
Jan;
like MySQL, OF
Data Manipulation Language (DML) and Data Query Statements.
also to eae and exploit the relationship between stored data. Additionally, these databases
ase normalization rules for avoiding redundancy of data. Python programming
guage has powerful features for database programming. Python supports various databases
acle, Sybase, PostgreSQL, etc. It also supports Data Definition Language (DDL),
But Python standard library
does not come with an RDBMS interface. For database programming, the Python DB-API is a
widely-used module that provides a Database Application P:
standard for database interfaces. Database Applica!
used by an Application program to communicate wit
such as Database Management System. These APIs are
de linkage to the required program to perform a task.
pro;
Most Python database inter’
We can choose the right database fo!
of di
grams which provi
Jatabase servers such as—
GadFly
mSQL
MysQL.
PostgreSQL
Microsoft SQL Server 2000
Informix
Interbase
Oracle
Sybase
faces adhere to this standard.
1" our application. Python Dat:
rogramming Interface. It is a
tion Programming Interface is a set of tools
rh the Operating System or other programs
implemented by calling functions in the
base API supports a wide range8.2 PYTHON-MySQL CONNECTIVITY
While designing real-life applications, certain situations arise pertaining to storing som,
important and necessary information by the user. Usually, the data inputted by the user alo,
With the generated output is displayed but not stored because all program execution takes plat
inside the RAM which isa temporary memory and as soon as we close the form, its conten,
(form input and generated output) get erased. They can’t be retrieved since they are not saveq
ona hard disk (or any secondary storage device). Thus, when the application 's executed the ney,
‘a now set of inputs from the user. This limitation can be overcome by sendin
‘4 from the user in a database created at the
het
d from the user using Python Interface. This jg
time, it requir
the output generated and saving the input fete
back-end of the application. The input is fetches
termed as the Front End Interface of the application.
ront-end (Python) and Back-end (MySQL)
Fig. 8.
Database (The Back-End)
red to save data permanently on some secondary
While working with an application, it is requi
so that stored data could be used for future
storage device, which is usually the hard disk,
tion and retrieval. An application usually stores a lot of data in the
ctly accessible to the user. This database is used by the
reference, modification, dele!
d Back-End Database.
form of a database which is not dire
suitable response to the user. This database is calle
we learnt how to create databases, tables and how to perform query processing on
these tables using SQL commands like CREATE, UPDATE, ALTER, INSERT, DELETE, SELECT and
$0 on in various forms according to their specific syntax structures. We shall be implementing
all these DDL and DML commands of SQL through Python Interface.
application to give
In Chapter 8,
8.3 WHY PYTHON
grating MySQh
Python isa flexible, portable, easy to learn and modifiable language. So, we are inte
with Python interface for executing any database applications. ‘The various reasons to use Pythor
for programming database applications are:
* Programming in Python is arguably more efficient and faster as compared to other language
+ Python is known for its portability.ports SQL cursors,
Jython suPI
af rrany programas
mm ised connections of the
closed f the database to avoid further i A
er exceptions and
a rn
an connections 3 taken care of
th! .
pytho”
a tabase APIs are comp: i
‘yon ire compatible with various databas svery easy to migrate
fs bs Catabase application interfaces, ious databases, so itis very easy to BEA
of the open
guages,
In Python,
the applicati
PPlication developer needs to take Care
ors.
, supports relational databa:
and
STALLING MySQL-CONNECTOR
34 IN .
. i ,
so estlish ca eee Python and MySQL, we require Python Database Interfaces
j apls: We mus ad a separate DB-API module for each database We need to access.
es using Python structures
rovides a minimal standard for
oa ewes 3 pleauierd for working with datal
Bex wherever possible. This API includes the following:
an
2 porting the APL module
acquiring @ connection with the database
issuing SQL statements and stored procedur
* Gjasing the connection
ate goal is to connect Python with MySQL. To do this, we need to install
tall the connector and connect it to Python are explained below:
ysql-connector using ‘Pil
pur ultim a connector.
steps to ins!
‘To connect Python to MySQL, we have to install my
on the command prompt (cmd).
step 1: p’ command
ES ‘Command Prompt
Pere triers teeresen esr 7600)
|i re tee erat
| ees
| Reece Naoto
bs \Ueers\preetaNappData\Localzed Prograne
RON tae Natr ena
SENN erro nana Ke
Pierce Ge
SEN eet
Eee
e:\Users\pre
NaN:
Fea Cannot Fi
Pe erEN DDE Nt
Pe rate rN NP
NaN ae
\Usera\preeti\appDat
nnector is installed in the sam‘
lote: Do ensure that mysql-co! e folder as Python and takes the
path as—
cd C:\Users\your name\AppData\Lo
2\Scripts>
cal \Programs\Python\Python37~
er 5Step 2: Once you have set the path, type the command as—
python -m pip install mysql-connector
or
pip install mysql-connector-python
ia Command Prompt
SST EN TET ETT)
io: \Usors\preeti\AppData\Local\Prograns ed) Python
s rx aT ed
lo :\Ueore\proetiNAppData\LocalPrograits
ed Python37-32
Ios\Usewe\preetd\AppData\Local\Prograns\Python\Python37-32>ed Seripts
oi \Usere\pres €iNAppData\Local\Prograns\Python\Python37-32\Seripts>python —n pip
Fae ER LS
5
Downloading Nttps:7/Files-pythonhosted.ong/p:
RU Pe aR ETE rE Per a at es ace eae cSt
SNe eee eee eee eee ee irre atichi: 73 bl
| Reet aero ere ay
EEN a SOP MEE Ten atch
Racer b Rehr we CR Ue reece
Stee cecaltert ister Chie UR ae sree CLIC AC eee LTP nL OO
Sue cei e oor aa enyNeNN CT Po Tia tates eles Uma)
\Users\preeti\AppData\Local\Prograns\Puthon\Python37—32\Scripts >
Mysql-connector shall download and will be installed on your system. Now we need to check
whether it has been properly installed or not.
Step 3: To do this, type import mysql-connector in Python shell. If no error message gets
displayed, this signifies that driver has been successfully installed.
[>>> import mysql. connector
>>>
Ina nutshell, three things are to be kept in mind for the successful installation of mysql connector:
> Ensure that Python has been already installed onto your system.
> Incase there is no Python installed prior to connectivity, download Python 3.x and then install
it,
> Download MySQL API, exe file will be downloaded; install it.
> Install MySQL-Python Connector
> Now connect MySQL Server using Python.
‘CTM: MySQL Connector Python requires Python to be in the system's PATH. Installation fails if it doesn’t
find Python.
Alternatively,
We can also establish the connectivity through the module “MySQLdb".iscuss the b
ros st discuss the basic concepts relateq to Mysqu
al
ja mysatdt .
quid is an interface for connecting tg
a
implements the Python Dat
i
MySQL dat:
abi
‘abase API and is built on toy
‘ase server from Python.
P of the MySQL C API.
It
What is
Connection?
ly
Fig. 8.2: Components of MySQLdb-
python-MySQL Database Access
MySQLdb is the Python interface to work with MySQL databases. It must be imported in Python to
work with any MySQL database, To import MySQL for Python 3.x, first, the module MySQLclient
needs to be installed as follows (assuming Python is already installed with pip and its path
included for Windows 8 or 10):
} Open a command window (cmd).
> Type the following at the command prompt:
pip install mysqlclient
After mysqlclient is installed on your system, MySQLdb needs to be imported as shown below:
+ Open Python shell at the command prompt:
¢:\>Python
+ Import MySQLdb in Python shell
>>> import MySQLdb
Ifthe above command produces the following result, it means MySQLdb module is not installed.
Reeeeerecs es
peceee en ues
aay cone
febatees ener u has
ey
If the above error occurs and the mysql module for the Python version you are using is not
installed, it can be downloaded from:
http: /sourceforge.net/projects/mysalpythonThis is followed by establishing connection
and creating objects for interacting with
MySQL using Python. Therefore, mysql-
Connector installation, which we have discussed
in the previous section (8.4) is recommended
for use,
merning Tip: Connector for Python—
a ne
sr fnanaging all your MySQL products, iniugi?
MySQL-Connector/Python, with MySQL Installers pd
wyemmended approach.tt handles all requiremer®
seco ryavequlsites, configurations and Upgrades,
lly implementing SQL comm,
ysql client program which is running at th
swe arenetaean tt
One more thing to be taken into account is that before actual ands
through Python interface, we can check for the m
f i time:
back-end of the program. To check for MySQL user, about which someti
the following command can be executed on MySQL prompt.
mysql>SELECT current_user ()/
This command shall display the username which is running on MySQL client program.
iF} €\Program Files (x86)\MySQL\MySQL Server 5.1\bin\mysal.exe
TCT ee
Ree reco a
Sere Pe BCC aca aa
‘ype ‘helps’ ox ‘\h’ For help. Type ‘\c’ to clear the buffer.
Stas Seas
i
i
oor tieeri: Stare ry
8.5 ESTABLISHING CONNECTION
After completing the first step of installing mysql-connector, the next step to using MySQL in
Python scripts is to make a connection to the database that you wish to use. All Python DB-AP]
modules implement a function:
‘module_name.connect’
This is an essential function required to connect to the database, which is MySQL in our case.
Note: Ensure that the username and password you are entering for MySQL should be correct. We
have used “root” as username and blank (“”) as password for all implementations connectivity.
Practical Implementation-1
To establish a connection between MySQLdb and Python:
Create the first program in Python script mode for establishing this connection. Open a new
script file’in Python, type the following script and run it.
mydb = mysql.connector. connect (host=" localhost", user=root", passud=")
i] print «mydb): Connector for Python—
Learning Tiynector/Python on Microsoft Wing
Instat ing all your MySQL products, inet’
jysaL-Connector/Python. with MySQL Installers qa
recommended approach. It handles all requitemen
wad prerequisites, configurations and upgrades
followed by estab
and creating objects for interact
MySQL using Python, Therefore, my’
connector installation, which we have dist
in the previous section (8.4) is recommended
for use.
ishing connection
ing with
al
« that before actually implementing SQL commang,
for the mysql client program which is running at th,
hout which sometimes we are not aware ge
One more thing to be taken into account
through Python interface, we can chec
back-end of the program, To check for MySQL use
the following command can be executed on MySQL prompt:
mysql>SELECT current_user ()t .
ame which is running on MySQL client program,
This command shall display the usern
Ty CAbrooram Files (x86) MySQL\MySQL Server 5.1\bin\mysal.exe
Ng
Roa Ay
SCS a eee eC SA CCA Re aan
ony Rice’ as
uctag rere es aero
Server version: S.1: a
Sears EN nary ee rN CoC ao
Eee CR Cer
Stern
8.5 ESTABLISHING CONNECTION
After completing the first step of installing mysql-connector, the next step to using MySQL in
Python scripts is to make a connection to the database that you wish to use. All Python DB-API
modules implement a function
‘module_name.connect’
This is an essential function required to connect to the database, which is MySQL in our case.
Note: Ensure that the username and password you are entering for MySQL should be correct. We
oot” as username and blank (“") as password for all implementations connectivity.
have used
1
To establish a connection between MySQLdb and Python:
Practical Implementa
Create the first program in Python script mode for establ connection. Open a new
script file’in Python, type the following script and run it,
[LS ec ONT CTR ONT TIRES EM
fone Re Ooo ee hee
import mysql.connector 7 —
hing th
f
5
mydb = nysqi.connector.connect (host:
print (mydb)
localhost", user="root", passwd="")aunow understand the above commands in deta
i ; .
tis to import mysql.
statemen| sql.connector .
ip Byte The next statement involves thean Sear ser pe we eg already sai instar oa
om an vty gets established through | Teation of a connection object ‘mydb’ once the
e
oc
ante) in our Case. alhost for MySQL with username as ‘root’ and password as
rqplans j
: this statement is executed successfully,
: ,
one mydb connection object is created and the message
y LConnection object at 0x03335470>
“saisplayed. else e*FOF message is displayed,
j connector connection .Mysg
a: The connect() method creates a connection to the MySQL server and returns a MySQL Connection
object,
thus, the following steps are to be followed while connecting your Python program with MySQL:
. Open Python.
+ Import the package required (import mysql.connector).
+ open connection to database.
« Create a cursor instance.
. Execute the query and store it in ResultSet.
+ Extract data from ResultSet.
+ Clean up the environment.
8,6 CREATING CURSOR OBJECT
The next step for interacting with MySQL through Python is to create a cursor object. It will let
us execute all the queries we need. Thus, in order to put our new connection to use, we need
to create a cursor object. It is a useful control structure of database connectivity. When we fire
sry data manipulation query to database, it is executed and the result set (set of records) is sent
aver the connection in one go. Although we may want to access data one row at a time, query
processing cannot happen one row at a time, so cursor object helps us perform this task. The
cursor object stores all the data as a temporary container of returned data and allows traversal
so that wegan fetch data one row at a time from cursor.
The cursor object is an abstraction specified in the Python DB-API. It gives us the ability to have
‘nultiple separate working environments through the same connection to the database.
We need to create the object of a class called cursor that allows Python code to execute database
‘ommands in a database session.
Cursors are created by the connection.cursor() method: they are bound to the connection for
the entire lifetime and all the commands are executed in the context of the database session
Wrapped by the connection.sow understand the above commands in detail
te et stateme ysql.connector into your script, which has already been installed
fi 39st lished th a the creation of a connection object ‘mydb’ once the
ot ivy Bets © ough localhost for MySQL with username as root’ and password a5
ea) in aut CaS
cethis statement is executed successfully, mydb connection object is created and the message
i :
. seapecomnector connection HYSOLConnection object at 0x033B5470>
an paged else e77OF message Is displayed,
es
te connect!) method creates a connection to the MySQL server and returns a MySQL Connection
object
us the following steps are to be followed while connecting your Python program with MySQL:
"open Python.
* mport the package required (Import mysql.connector)
| open connection to database.
|. create a cursor instance.
Execute the query and store it in ResultSet.
Extract data from ResultSet.
Clean up the environment.
3,6 CREATING CURSOR OBJECT
the next step for interacting with MySQL through Python is to create a cursor object. It will let
us execute all the queries we need. Thus, in order to put our new connection to use, we need
te create a cursor object. It is a useful control structure of database connectivity. When we fire
aty data manipulation query to database, itis executed and the result set (set of records) is sent
ver the connection in one go. Although we may want to access data one row at a time, query
processing cannot happen one row ata time, so cursor object helps us perform this task. The
cursor object stores all the data as a temporary container of returned data and allows traversal
so that we.gan fetch data one row ata time from cursor.
The cursor object is an abstraction specified in the Python DB-API. It gives us the ability to have
multiple separate working environments through the same connection to the database.
Weneed to create the object of a class called cursor that allows Python code to execute database
commands in a database session.
* Cursors are created by the connection.cursor() method: they are bound to the connection for
the entire lifetime and all the commands are executed in the context of the database session
wrapped by the connection.
“~~
We can create a cursor object by executing the cursor() function on our database object.
Establishing the connection with MySQL database requires the following steps to be execurs,
(Fig. 8.3):
1. Use mysql.connector.connect() method of MySQL Connector Python with required parame,
such as host name, username, password and name of the database to connect to Mysqi_
2. Use the connection object returned by a connect() method to create a cursor objectto Perform,
database operations.
3. Use/type the cursonexecute() to execute SQL queries from Python.
4, Close the Cursor object using a cursor.close() and MySQL database connection Using
connection.close() after your work gets completed.
5. Catch Exception if any that may occur during this process.
Python DB | Python DB API v2.0 (PEP 249)
API
1 mysql.connectorconnect()
mysQu
Connector
Python |4 —_connection.cursor()
[python
Application
5 __Cursorexecute(query)
Fig. 8.3: Python-MySQL Database Connection
Arguments required for connecting MySQL database with Python: :
> Username: This is the username that you use to work with MySQL Server. The default
username for the MySQL database is “root”.
> Password: Password is given by the user at the time of installing the mysql database. If you
are using root then you won't need the password.
> Host Name: This is server name or IP address on which MySQL is running. If you are running
on localhost, then you can use localhost, or its IP, i.e, 127.0.0.0
> Database Name: It is the name of the database to which connectivity is to be established. Here
we are using a Database named ‘school’ which we will be creating in the upcoming section.
8.7 CREATING A DATABASE
Once the connection gets established, our next step is to create the new database ‘school’ in
MySQL through Python. Before creating this database, it is advisable to check whether this
database already exists or not. This is done by typing the command—
SHOW DATABASES;
in the front of MySQL prompt (mysql>We can create a cursor object by executing the cursor() function on our database object,
Establishing the connection with MySQL database requires the following steps to be execute
(Fig. 8.3):
1. Use mysql.connector.connect() method of MySQL Connector Python with required paramete,
such as host name, username, password and name of the database to connect to Mysqy,,
2. Use the connection object returned by a connect() method to create a cursor object to perfor,
database operations.
3. Use/type the cursor.execute() to execute SQL queries from Python,
4. Close the Cursor object using a cursorclose() and MySQL database connection using
connection.close() after your work gets completed 8
5. Catch Exception if any that may occur during this process.
Python DB API v2.0 (PEP 249)
1 mysql.connector.connect()
a SS
mysQu
Connector
Python [4 _connection.cursorl)
[——___*\_ Python
Application
5 Cursorexecute(query)
EF EOErre—evewe
Fig. 8.3: Python-MySQL Database Connection
Arguments required for connecting MySQL database with Python:
> Username: This is the username that you use to work with MySQL Server. The default
username for the MySQL database is “root”.
> Password: Password is given by the user at the time of installing the mysql database. If you
are using root then you won't need the password.
> Host Name: This is server name or IP address on which MySQL is running. If you are running
on localhost, then you can use localhost, or its IP, ie., 127.0.0.0
} Database Name: It is the name of the database to which connectivity is to be established. Here
we are using a Database named ‘school’ which we will be creating in the upcoming section.
8.7 CREATING A DATABASE
Once the connection gets established, our next step is to create the new database ‘school’ in
MySQL through Python. Before creating this database, it is advisable to check whether this
database already exists or not. This is done by typing the command—
SHOW DATABASES;
in the front of MySQL prompt (mysql>).evident from the above screenshot, no database named ‘school’ exists. So, we will now
Sepate 2 database named ‘school.
practical implementation-2
qo create anew database ‘school’ in MySQL through Python:
qnis is done by 9 ping the command “CREATE DATABASE "” after establishing
Tn onnection and creation of cursor object. In our example, it will be:
«CREATE DATABASE school”
in new file created using Python script mode
peas Cot een appari egret eT Types stern oy Go. taal
=jusers*zoot™-passud="") |
my
on successful creation of this database, if no error is displayed and the cursor starts blinking in
front of the Python shell, this signifies that database has been successfully created.
We can further check the creation of database ‘schoo! by typing SHOW DATABASES; command
{QL prompt. The screenshot given below shows that database ‘school’ exists.Unnissmontirg Ste ean RSA DAS CORTON Pre
SENSES SAA Soren ;
: awe NAAN NN YAN
DS Te a RNR TREN, RAHA TNO MOT HN NUT PERE NTT NT TTA tg
FRR TRAES RD WD AHANT NOS
SSO TNS SEMAN BIN, FANS HUNT NAAT DN TANI
SHAHN FMS Th
S Tystonnrnare Teer DHEAT NES
SENSES DOP aRY Whey SAAN NW
Dea FRAN DENI BANOS Wo
pe SOW HS AD STH WHO WH BAL Fam ong
Sawn WO WATT WHEY Ute hata,
2) SALINE AY PONE | WHIT,
NN0,
= Spa geemecess Senet ()
= USSaStimctinn wROaR HAART ASH Database Hi Tanelion aavephs fy WMI
ESR SER RA NN ESD, TSOP IN) RASA WONT DAL WE NWT ATUL Have OA,
oe
= sommect) Gumsian AGSNIShes 2 cammation fy The MYSTE datahase Home Athan
SaMnIGatinn and SCucns b MSN Cannnsinn adees, Than wee oan vse MYSQLConneetan
QHECT Ie FETE WINS ApETATians on The MySQL, Datadare,
= smmact) emcinn can Shope an aoa AA, Fa, Database erhyy (one of the requitod
FEREMENS MEANS. RAT ENRTAP, TY oa AatAdAse NANO Nt is HOt pHovent
mm ARQ. Shem Dachan AnAheaTiAn PAWS an NPT,
prt.
Se, Shek She angumonss Shek YOR ae PASsAg W This Aetion,
= Ss_oemsee i)
> Some:
crectip ff nur Fychan anghoadan fo
<3) & She emstion ©
QEEomMSetion Class eowugh whieh we ean
A ty MYSQL, This Qinetion vous Ne ih
ras Balsa,
cmmmestinn & ssonhhshad, scharwise me
= sommes ori
+ Tsmesnninsict so
Sar Sher, USAR A cUrsT HH}eet, we ean evecuty SOL queries,
+ Th WRU
Sass Snstantiates adjacts That ean evecute operations such ay SQh
Camsor qihiects Insecact with the NySQL server using a MySCL.Conneetion objec
Tsualiy = sumsot mm SQL and Gatwhases is a Control structure to traverse over the records
= EeGIMASE Sp if Ss aed for Fetching the results. We get the cursar object by calling the
curso) mechné of cannection. An arbitrary number of cursors can be created, The cursor
as assed Ip Sevens the records from the result set.
Same: The sxeruze{) mechad arcepts arguments of SQL statements in Swing torn
am dimitie gumeas, Srgement can de usad in any one of the forms: U
Sails qumes ["} slang with semicolon () or use SQL s
Gp che ahows rramam, corsar Sbjct which is “mycursory is used ty execute Create Databane
command asm Python shell, Moreover we have verified the creation of the database fron SQL
1, Le, enclosed
© SQL statements i
tatements without semicolon (}):
a eeUnderstanding the Python MySQL Database Connection Prog!
import mysql.connector
ctor Python module in your program so you can ys
+ This line imports the MySQL Connes
this module's API to connect MySQL.
or shall be displayed—
In case the connection fails, import er"
from mysql.connector import Error
1 to show us an error when we fail to connect
» error occurs while working with the database
ame or password is wrong,
+ mysql-connector Error object is us
pases or if any other databs
R_ACCESS_DENIED_ERROR when U
“ mysql.connector. connect ()
dat
Example
his function accepts four
ady discu
equired
«Using this function, we can connect the MySQL Database;
ed.
Jost, Database, User and Password that we have alr
parameters:
ur connect ()
+ connect() function establishes a connection to the MySQL database from Python
application and returns a MySQLConnection object. Then we can use MySQLConnection
object to perform various operations on the MySQL Database,
connect() function can throw an exception, i.¢., Database error, if one of the required
parameters is wrong. For example, if you provide a database name that is not present
in MySQL, then Python application throws an exception,
ing to this function.
So, check the arguments that you are pass
“ conn.is_connected()
connected() is the function of the MySQLConnection class through which we can
verify if our Python application is connected to MySQL. This function returns True if
connection is established, otherwise returns False.
@ connection. cursor()
« This method returns a cursor object. Using a cursor object, we can execute SQL queries,
+ The MySQLCursor class instantiates objects that can execute operations such as SQL
statements.
Cursor objects interact with the MySQL server using a MySQLConnection object.
@ cursor().execute()
Usually, a cursor in SQL and databases is a control structure to traverse over the records in
a database, So it is used for fetching the results. We get the cursor object by calling the
cursor() method of connection, An arbitrary number of cursors can be created. The cursor
is used to traverse the records from the result set.
Note: The execute() method accepts arguments of SQL statements in String format, ie., enclosed
in double quotes. Argument can be used in any one of the forms: use SQL statements in
triple quotes (’”) along with semicolon (;) or use SQL statements without semicolon (:)-
‘mycursor’, is used to execute Create Database
In the above program, cursor object, which
command using Python shell. Moreover, we have verified the creation of the database from SQL.
_——y gone frome Python also as discussed in Pra -3.
e in Practical Implementation-3.
zbove cade, the output wi : .
code, the output window shall display all the databases present in
for loop hes been used to traverse among all the databases present inside ‘
Gat Wa can exzeute the SQL queries from Python program using Gracute) method associated aa
‘gchoo!’ database in MySQL, our next step is to create 4
the creation of
2 through Python shell.
Practical Implementation-+
de the database ‘school’ using Python script mode as the interface.
scudent insi
Type and run the given command of
MySQL in Python.If no error is display
by using dese command, ic., dese student
the structure of the table student in MySQL.
d, this means the table has been sucee
Han Sta ea
pera Cmca!
a oe co
ine | a
Perrenr cece tity
ysal>
This can also be done directly from Python shell by typing the se
Implementation-5.
Practical Implementation-5
To check for the created table ‘student’ using Python.
sort mysql .connector .
nydb = mysql connector .connect (host="localhost"y\
ycursor = mydb.cursor()
nycursor execute ("5ilow TABLES
}
x in mycursor: |
Prineoo }
In the above program, SHOW TABLES command in SQL is executed u:
“mycursor’ in Python script. This shall display all the tables present ins
by using for loop for traversing all the tables pr
as shown below.
RESTART: C:/Users/preeti/AppData/Local/P
rograns/Python/Python37-32/prog_sqlpyth2.
py
Cstudent',)
Similarly, we can implement any DDL (Data Definition
Python.
Implementing DDL Commands using Python Shell
We will be discussing an important DDL command in SQL to modify the structure of the
already created table ‘student’ using ALTER TABLE command in Python script.
esatully created and ean be veritigg
ny MySQE prompt which shall yyy
ipt given in Practica,
ing the cursor object
de the database school
ent inside it and, hence, the output is obtained
nguage) commands in MySQL using
~and ca be veriting
as been successfully ereat
a hich shall dig
If no error is displayed, this means the table
ab ese student; in MySQL prompt w
by using dese command, i.e. (
the structure of the table student in Mys
aeheeennets
Rim mic
y 1 NUL
ES eit
Hee: uit
yous in eet 0.13 sec?
ied
given in Practica,
This can also be done directly from Python s|
Implementation-5.
-5
Practical Implementatio
To check for the created table ‘student’ using Python.
inport mysql -connector
yap = nysqi connector .connect (host="1
¥ yes user="root",\.
passwde",\
Batapasow*achool")
mycursor execute ("sHow TADLES
for x in mycursoy
|
|
|Jnycursor = myud.cursor 0)
|
|
°° Princo 7
SQL is executed using the cursor object
In the above program, SHOW TABLES command in
ent inside the database school
‘mycursor’ in Python script. This shall display all the tables pres;
by using for loop for traversing all the tables present inside it and, hence
as shown below.
, the output is obtained
RESTART: C1/Users/preeti /appData/Local/P
rograms/Python/Python37-32/preg_sqlpyth2.
Py.
Catudent*, )
Similarly, we can implement any DDL (Data Definition Language) commands in MySQL using
Python.
Implementing DDL Commands using Python Shell
re of the
We will be discussing an important DDL command in SQL to modify the stru
already created table ‘student’ using ALTER TABLE command in Python script.(adding a new column) in
gnysol sin terface
{mport mysql -connector
mya = RYSql-comnector connect (host:
nycursor = mydb.cursor()
RYCUESOE -eXeCUEE
‘RLter table student
gra spayed amd the cursor nthe font of Python shell starts blinking, it indicates
ae TUDE student has been successfully modified. This can be verified in
cath ng DESC STUDENT: and aso using Python shel a5 we ‘will take up in Practical
weak petattoné7-
ical mpplementation-7
view
¢ mysql connector
mysql sconnecter-connect (host
passwd
Satabass
mycursor = eydb.curser()
ete trbese sttd
npycursort
cy
upon the execution of the above script, the following output shall be displayed as shown in the
screenshot given below.
RESTART:
python Py
(Roline, ine)"
(Mane", tvarchar(15)"
(ager, int an)"
qeity!, tehar (8)
Gnarkst, int)", "¥8st, "None, 1)
4s shown in the output displayed, the structure of the table gets displayed in the form of tuple
of strings.
ne next step is to populate this table, ie, insert a record into the table student using
SERT INTO command through Python Interface.
Inserting Records into Student Table
AM
é ne the table student has been successfully created and altered, we will add records to it using
Popular SQL-DML (Data Manipulation Language) command INSERT INTO using Python shellPractical Implementation-8
ert a record into the table student using Python Interface,
RESTART: ci/Users/preetivapptatasiocal/
fans. Tytbon FytSORS “32 PEG AYP
We can veri ECT statement in My
+ The cursorrowcount is the property of cursor object that is used in the given program and
shall return the number of records inserted which is 1 in our case since we have inserted
only one record into the student table.
+ For storing String data type values, all the string values should be enclosed in single quotes,
We can insert multiple records also at the same instance through Python.
Practical Implementation-9
To
‘ert multiple records into the table student through Python interface.
1, +390)")
ka", 18, "shimia’, 382)"
joa", 300)*)
4109")
13857)
B.coenstBrome: CAtetiterOeoatomu ent peastes
fue et format Rin Opvow Wow Help neyosar
2 ye. anne
fe jsqh.connector .connect (host
a
leciteat
Beatie tierce)
Hes
jn the above code, we have used a function commit() which we will discuss now.
Pn
INSERT and UPDATE operations are executed in the same way we execute SELECT query using execute(),|
However, We must remember one thing: after executing insert or update query, We must commit our query]
{ging connection object with commit(),
Forexample, (if our connection object name is mycon)
mycon-commit ()
‘his statement is required to make changes in database permanently; otherwise, no changes are made
to the table. :
Methods to Manage MySQL Database Transactions in Python
python MySQL-Connector provides the following methods to manage database transactions (Fig. 8.4).
commit: MySQLConnection.commit() method sends a COMMIT statement to the MySQL
server, committing the current transaction.
«rollback: MySQLConnection.rollback{) reverts the changes made by the current transaction.
+ autocommit: MySQLConnection.autocommit value canbe assigned a5 ‘True or False to enable
ar disable the auto-commit feature of MySQL. By default, its value is False.
Transaction
succeeded
Al Queries
executeds
successfully
‘Transaction
{Query 1,
Query 2
initiate
transaction
Any of the
Query n) Queries failed
® Transaction
failed
Fig, 8.4: Python-MySQL transaction management using commit> Syntax of commit() method on
Once a program has completed executing meaner wave
the changes to the database, then you need to calll co.
object as follows:
changes and you want to commie
method on MySQL connection
connection. commit ()
> Syntax of rollback() method
undo all your ct
When one ofthe transactions fais to execute and you want to revert or undo all Your changes,
then you need to call a rollback method of MySQL connection obj
connection. rollback ()
That was all about transaction handling using Python-SQL. connectivity.
In Practical Implementation-8, after multiple records have been pee brea te table Student,
it is checked using SELECT statement in SQL. This can be accomplished in Python as well.
Practical Implementation-10
To display all the records of student table using Python shell.
inport mysql connector
Jnydb ~ mysqi ‘connector.connect (host="iocalhost",\
nya = mysqi ho
passwd", \
Satabaze="achool")
Inycursor » mydb.cursor()
mycursor.execute ("select * from student")
mysecords = mycursor.fetchall()
for x in myrecords
Print
RESTART: C:\Users\preeti\appoata\zocal\Progran
s\python\Python37-32\prog mysqipythe.py
(Q, "Tarun, 23, tmunbai'; 398)
(2; "Pooja, 21, ‘chaii', 390)
(3, ‘Radhika', ie, "Shimla, 386)
(4, ‘sonia, 24, toa, 300)
(S, ‘Vinay*; 25, ‘pone! 410)
20, *snaurya", "15, "Deinit, 345)
In the above program,
function is used to read
READ Operation
we have used SELECT statement along with fetchall() function. This
and display all the records as tuples from the table student,
fetchone(): It fetches one row from the result set
in the form of a tuple or a list. A result set
is an object that is returned when a cursor obje
ct is used to query a table. This function
, Le., first time it will return the first record, next
time it will return the second record and so on. If no more record is left in the table, it will
return None.- fe fetches all the r
2 a eect fs ‘Ows in a result set and .
ire Or om the result se returns a list of tuples. If some
ae get FTO MOTE TOWS are available ity
“rangi size) Ie fetches the specihed ann
1 Ee dotale site is Tif there are a
ds, it will return an empty let.
aeser
ant: This is a read-only att
owe s ribute and
remecute() method and retrieved from ears the number of rows that were affected bY
2 om method. all UrSOT.
gechall method, all the records ret:
“precords’ which we can
display
isplay one by one using for loop.
ie
. mentation~ Sficati
ee feel _ = 11 (Modification of Practical Implementation-10)
spall the records along
‘with the total numberof records from student table using Python shell
sprog sya
\agqeaca zecal seoqeans zynen\sysen2?~
ig 2 modification of the previous implementation. It displays the total number
of cords retrieved from the table ‘student’ apart from all the records being displayed. The
umber of records fetched is displayed using the attribute of the cursor object, ie, rowcount.
ss the number of records retrieved from the table and the output shows the
yed alongside.
This program
ich are also displ
oral mmber of records i
tig evident from the output screenshot, the records are displayed one by one as a tuple. We
- the records row-wise as well instead of a tuple.
fy the for loop control variable as shown under:pant fetes al th
\!
AN A nt
A HONEL ay
pete iy hee oxtraetod fone-the rout mh WHE OLTHG A Hat af tupen, Hanne raven hive!
+ eal . ML Then He pe .
ave 0 ANOHE HOU i ‘olin "A Wit Fay owe HU
w (atzo)e I fotchon the apecttio ‘AN empty Hat
wt aaa lame pul) OOF How (ia Dt af Lapphan) fram the regi
. phe: are ‘Own My
ee Hyori WHE FLUE A om ty Hat We romutt wot, an eanpty Hat) be retuened 1
oll " ‘
1: This bv a readonly attrtbute ane
pve \ Hd HOH eH hee nnn r ayes iattocten
, vette) et a ete Ha th ue Wnihor of raven that yore altuetod by
a won
calf) metbon all he record pot
f
ved! {rons the table ai
ty wel wo enn liplay ong vin tHe table stacdowst shall gat tore ny the
hy one using fav loop,
implementations H (Moditication ofp
x Tactical Lmplementation= 10)
iyallahe recor along, with the total number af recurs
from student table using Bythion shell
ca iy ca
rane
aaa
reeh tu iw. tah
sport yn comet |
|
|
seems |
Po myeecordat ! |
print 00 START? C1\Usera\preot \A |
oot apbata\tacalerenn ryem\epemst rp wae
pte rans rnenver |
ital nn ot raat tot anes 4 |
(iy sataivariny oH", tela (040), Aabatinn tata, 96 47h, Haina — |
t2, Sabaint'y ss, vacinateeTiasibs tat nevtotetzii, 3 28iy Shana") |
(5, "toonnt, 1H, fecal 163,00"), datetine tate (20hy % tanh |
{ih seinturs ery Imclnal esose), wenay oath) |
this program is a modification of the previous Implementation, It disy
ofrecords retrieved from the table ‘student’ apart from all the records being, displayed, The
number of records fetched is displayed using the attribute of the cursor object, Le, rowcount,
This attribute counts the number of records retrieved from the table and the output shows the
total number of records as 4, which are also displayed alongsi¢
ys the total number
Asis evident from the output screenshot, the records are displayed one by one ay a tuple. We
can display the records row-wise as well instead of a tuple.
To do so, we have to s
ghtly modify the for loop control variable as shown under:
iy ocorly IwAbnvdinlly 18 Fo
tigate
nycucane = wych.cursor 0
tatmietent © frm stutent")
foterall
ain ony By Se At, BYE
Ot eng ens ees, 8021) (55
PeataeTs Cr\Useeripeonthvayyians
1 F 78.00" 202.0%.
tans M8300 2004-05-11 balhd
1 eines 710.0% Won Cand() in between the data being disp
Another representation of the records using separator
as reconds is shown below:
Practical Implementation-12
To display records from student table, one at a time (using fetchone())-
we fetched and displayed all the records from the student table.
method to fetch and display the records fro,
Till the last implementation,
this implementation, we will be using fetchone()
the table one by one or one at a time.
Practical Implementation-13
To display ‘n’ number of records from student table (using fetchmany(n)).
‘This program shall fetch and display ‘n’ number of records from the table through fetchmany
method by passing the number of records to be retrieved as ‘n’.
In the above program, three has been passed as an argument to fetchmany() method and, hence,
the output displayed shows first three records from the student table.AQOUNOE LO SHOONEALIAN AE Ue TEATS
opanitor (be betwen He data Hela, Ulsplayeg
AS Fevaetads Fo SANTA HOU
Aw so my yeeenslal
[OTA Sette noni:
prow Sra SE EOD
Gouna aviey aupneed agp ate EARN AN
Reval wes ee 4 M8) tS agg getme d
So wettoadd Leyptonien tation 02
Ry shisphay Wwentats Horne stator Ruble, ante al a Udine (using fotehone():
AAW Ure Last tinyphenrentation, we lotehedt at displayed all the records front (he student table, ty
AdAS Aan nlomontation, we will Be uusiys lotehaned) avethod to tote and display the records trom,
dhe Late one BW atte at aie a CH
LATTA NTA RATT MITRE
aoe
A Tahooty, sitet ime tte 2008, 9, 129, HwINLY
Practical Lmplementation= 13
‘dy adigplay iw’ mamber of reconts fhomt student table (using ftehmany(n)).
This program shall fetch and display"
1’ number of recor
method YP
s trom the table through fetchmany(n)
ing the number of records to be retrieved as ‘in
SRA AAS TTT TE
agentes (haat
soe yannonen ot yuananntenlatabases school")
otto
|
9 power agent a toa nog tas/FythoA/FYERSNAT TZ /PHO_ AST
ecuils fetsdat anes
SSNS Rocka (TES), Matet ime lat
Sis eNO, Ce
SCOOTERS
susan)
23) gana
ih)" sn)
ln the above program, three has been passed as an argument to fetehmany() method and, hence,
the output displayed shows tirst three records from the student table,
oeclate(aege, 5, 22)
ager ime dake (2008, 9,-aection using WHERE Clause
jeve selected
wwe can recieve selected records from the table using
goanner as iS done in MySQL Using WHERE clause in Python shell also in the same
practical Implementation-14
qo implement WHERE clause using Python intert
pis is to be implemented using ese.
MySQL S:
the given code: slect_Where statement in Python script as shown in
pycursor = nydb.cur:
EYSUESOZ-execute(”
In the WHERE clause, we have used city="Delhi, ie, to fetch the records of all the students who
are staying in ‘Delhi’ city. Since there is only one record in the table that matches with the given
criteria on, it shall be displayed as shown:
aS
cr /Users/preeti /apepata
at, 15, 345)
>>>
Parameterized Queries
Apart from entering the values statically in the program to search and display the records from
4 table, we can pass values to query to perform dynamic search, for example, to search for any
‘student roll number entered during run-time or to search for any other column values, etc.
To create a Parameterized query, any of the following methods can be used:
(2) Concatenating dynamic variable to query in which the values are entered
(b) String template with %s formatting .
(QString template with (} and format function ~
(a) Concatenating dynamic variable to a query
In this method, a dynamic variable is created that fetches the input for the field and passes it
to the query on the basis of which records are searched and displayed at run-time.
Iiereced suruIder and pass values to this placeholder by
fo sein template with (} and format functi
in this method, in place of % we us, rae
using format() function. As an ao Placehol
ent,
I we i
{0}.() for value] and value2 Tespectively, © can give 0,1,2... values but it is optional, eg.,
nnecte:
SE “Connect (hoste" ioe,
Gi 1OSte" Log,
cur:
+ database=
# C2/Users/prect.
ntineguery py + / MPPPata/Local /Prograns/eython/Python37~32/Pr03_
f,Zold mutber to be searches
: 1 (M's Pecizal(*s3,00"), datetime.date(2004, 9, 11), *Delhi')
Usingmultiple conditions
ng template with () aad Formac
rosers"root”,passwae"" database"
Parke >e[earks)" format (statenst,marks=mrk)
pret /appbata/Local /Prograns/Python/Pythen37-32/prog_mysql
9 search:Delhi
atching the criteria ar
Int, tM", Decimal ("83.00"), datetime.date(2003, 9, 12), "Delni"),
Tu, Decimal ("83.00"), datetine.date(2004, 9, 11), *Delhi')]
Inserting Records dynamically using {) and Format Function
In Practical Implementation 8 and 9, we have done insertion of the records statically. Insertion
of records can be done dynamically, ie., at run-time as well using {} and format() method.{insert recotds dynamically using 1) and Format O
sport mysql sconnector
Jexth 5 teat eomoctor connect gnoat=" 0ca1ho>
mycursor ~ mydh-cursord)
print mst Vinsertion")
thn input ("enter t
gheinput (reer
|] mexssint Ginpue center tne marie)
|] dbsinpat (inter the date oe birtnt)
steinput (renter state:")
query="insert. into student vatuns (10), " (14. 421% (ne 1A)
mycursor -exoeute (query?
nya. comet t()
DEANECHR Record (9) ad
Chofee=Input (Maint to sale
5) ) "format (rno, nm, gn, meks, db, st)
|
ay
|
|
|
Jusers/preeti /Appoata/Local
yth_insertaynam.py
Student. Record insertion
nter the rollno:
Enter
Entor gender:F
Enter the marks sae
Bntor the date of birth:2000/09/12
Enter state:Munbai
41 Record. (3) added... 44
Want to add more records:y
Enter the rollno:
Enter the nam
Enter gonder:F
Enter the marks:30
Enter the date of birth:1999/02/13
Enter state:Dehradun
@ Record (3) added.... 44
lant, to add more recordsin
jeetu
Deleting Records from a Table in Python-SQL.
DELETE operation is required when we want to delete some records from our table.
Following is the procedure to delete all the records from the table student for roll number 1.
Practical Implementation-16
Deleting records from the table student using Python interface.
[A proa.salpyih dett py - C/User/preet/AppOstahoc/Progir a. 3
ix Eat feat fan Opens inden i
jeleting ¥ecoras through Python Interface
import mysql.connector
nydb = mysql -connector .connect (host=" localhost", \
user="root", \
passwa="",\
Gatabases"schoo1")
Jnycursor = mydb.cursor ()
[nycursor-executa("DSLnTE FROM student where Rolino = 1")
fnydb. commit ()
print (myeursor-rowcount, "Record (s) Deleted")quis can be VerfTed USINE the statement. “
SELECT + nt; in MySQL.
‘CT * from student; in MySQL.
ee
Wecketanes
oe
fos
js is evident from the above output, the
not displayed.
record for roll number 1 has been deleted and, hence,
>
Rest : i 1
Syma: ©*/Users/preets/appoata/}
1 Record (s) Deleted |
updating Records in the Table using Python-SQL
vroat q een on any table means to update one or more records which are already available
in the table.
‘The following script updates all the records having Name as ‘Vinay’. Here, we increase AGE of
students with name as "Vinay" to 28 years.
actical Implementation-17
‘To update the student record dynamically using string template with %s formatting.
| \a *prog_salpyth_Updtpy - C7Usersuser
2iAppData/Local/Programs/Python/Python39/progs. —
File Edit Format Run Options Window Help
fupdating records
rough paraneterized query in Python interface A
Inport myaql -connector
Inydb ~ mysql -connector.connect (host="Localhost™,\
user="root",\
passwd="
database:
;chool")
[data (Age, Namo)
mycursor=nydb. cursor () i
query="UPDATE studen! set_age=ts where Name=ts"
mycursor.execute (query, data)
mydb. commit ()
print (mycursor. rowcount, "Record (s) Updated")
lee Coto)
3S
RESTART: C:/Users/preeti/Appbata,
>>jiscan be verified Using the statement-sezeon
rae * from
Student; in MySQL.
es
Fry)
i 388
Pence i Et)
CORN ne
BORCOKCR Tas
Bes
asis evident from the above output, the re
s cord f -
As played. d for roll number 1 has been deleted and, hence,
>>
RESTART:
dell.py
2 Record (s) Deleted
>>>
Ct /Users/preeti/appbata/)
updating Records in the Table using Python-SQL
UPDATE Operation on any table means to update one or more records which are already available
in the table.
The following script updates all the records having Name as ‘Vinay’. Here, we increase AGE of
students with name as “Vinay” to 28 years,
practical Implementation-17
To update the student record dynamically using string template with %s formatting.
# *prog.salpyth_Updtpy - C/Users/User2/AppDsta/tocalPrograms/Pythomythenssipegs. — O xX
Fie Edit Format Run Options Window Help,
fUpdating records through p:
eterized query in Python inte
port mysql.connector
nydh = mysql.connector.connect (host
passwd |
database=" sch: t
JAge=28 |
Nane="Vinay*
datas (Age, Name) }
nycursor=nydb.cursor () . t
query="UPDATE student set age=ts where Nane=ts!
mycursor.execute (query, data) |
ya. commit () .
print (mycursor.rowcount, "Record (s) Updated”) All
Let Coto
:/Users/preeti/appbata
updt py
i "Reccrd (a) vpeatea |
>>>‘This can be verified by checking the records in MySQL.
__ CAProgram Files. (BEN MySQLAMYSOL Server 5.1\bin\mysql.
no ee
era oC)
ves
As shown in the output window above, the age of the student ‘Vinay’ has been updated from
25 to 28 years.
Updating Records in the Table using Parameterized query
In the previous example, we updated the student record statically by passing the values to be updated
in the program itself, To fetch the values at run-time, ie, dynamically, we can use parameterized
query through () and format() method as given in the implementation that follows.
Practical Implementation-18
‘To update student record using parameterized query through {) and format().
[2 prog upeiate dmnamicl py » Cy Ucets/preeti/Appoata/local/Programs/Pyihon/Python3-32/prog update dynamic
le tat forma Pan Gptues Wot Mey
cally by fotehing input trom user at run-tine
aie
© mysql connector
nydb = mysq} :connector-connect (h host) \ i
record:")) |
()". format (rno) ,
nycursor.execute (query)
nyrecord-mycursor.fetchone ()
i myzecord != Non t
print ("es
Details are: #4")
pat ("Do to update marke: (y/n)")
marks: "))
() where roll_no=()". format (mrks, rno)
mycursor execute (query)
mydb.comeit ()
Print ("Hf Record (3:
else:
Print ("sor
mydb.close ()RESTART: Ct /Users/preeti /appn: ———
pamicl-PY ‘ppPata/Local/Programs,
aor ae gtams/Python/Python37~32/prog_upaate
Enter Follno to Update ‘the reco
ge Record Found- Details ares #7
(4, "Geetu'y "F*, Decimar(*90.00")
po you want’ to update marks: iyynyy
enter new updated marks:60, a
## Record (3) Updateats
4
datetine.date(i999, 2, 13), Dehradun")
understanding Python MySQL Parameterized Query Program
functii
we used the s ction Bsa. -connector.connect () to connect the MySQL Database. This
function accepts th avid Parameters: host, user, password and database. If a connection is
successfully established, it will return the connection object,
Firstly, we assign values to age and name variable which is to be inserted into the placeholders.
Then we create the parameterized SQL query. In this query, we are using two placeholders
‘ops’ for two columns in a table,
Next, we put two placeholders in update query, one for “name” column and the other for
“age” column.
We then provide values of age and name to the tuple variable input in sequential order and
pass it to mycursor.execute() function along with SQL update query. Remember, tuple
contains user data in sequential order of placeholders.
In the end, we commit our changes to the database using connection.commit().
Practical Implementation-19
‘To delete the record of a student on the basis of name fetched from the user at run-time,
executing deletion at run tine
fon the basis of user's input
import mysql connector
lant = mysqi.connector-connect (host="1ocalhost,\
user="root", \
passwd
database
||mycursor = dbi.cursor()
Wey einput ("Enter nane of the student whose record is to be deleted
Ilrreparing sol staterent to delete records as per given condition
fsqi’="Detere FROM student WHERE Wane = ‘nm')"
‘mycursor execute ("DELETE FROM student WHERE Name = ‘nm')")
Prine (nycursor.roweount,, "record(s) deleted”)
p1 -connit ()
except:
{bl rollback ()
RESTART: C:\Users\preeti\AppData\Local\Programs\Python\Python37
delesqlpyth-py
Enter name of the student whose record is to be deleted :Pooja
|| record(s) deletedPF cenRTt C1/US0r8/prontl /Appbata/tene y
aie PPPALA/ LOCAL /Progeams/Python/Pythond7~32/prog_upaate
ore Pa updat ton
Se crea irantaitte rao
ford Found- batatin aroe ey
vr, meetin,
eee akon aouingR
Eater ged tO) Dylatoaty
guverstanding Python MySQU, Parameter
red Query Program
‘This
we used the function mysql.connector.connect () to connect the MySQL. Database
function accepts the required parameters: host, user, password and database. If a connection is
suecesstully established, it will return the connection object.
«Firstly, we assign values to age and name variable which is to be inserted into the placeholders.
«Then we create the parameterized SQL. query. In this query, we are using two placeholders
ops’ for two columns in a table.
+ Next, we put two placeholders in update query, one for “name” column and the other for
“age” column.
+ We then provide values of age and name to the tuple variable input in sequential order and
pass it to mycursorexecute() function along with SQL update query. Remember, tuple
contains user data in sequential order of placeholders.
+ Inthe end, we commit our changes to the database using connection.commit().
practical Implementation-19
To delete the record of a student on the basis of name fetched from the user at run-time.
fon the basis of user's input
import mysql.connector
Jabi = mysql .connector.connect (host~
uuser="root",\
passwa="",\
database="school")
|Jmycursor = dbt.cursor()
ryeroct (antes name of the student vhose record is to be deleted :")
Tnreparing Sol. statenent to delete records as per given condition
foql ="DELETE FROM student WHERE Nome = "na')"
try:
‘nycursor.execute ("DELETE FROM student WHERE Name = ‘nn')")
print (mycursor.rowcount, "record(s) deleted")
I ‘dbi.comuit ()
excep!
‘bl -roliback ()
Jat .close()
33S
RESTART: C:\Users\preeti\AppData\Local \Programs\Python\Python37
delesqlpyth.py
Enter name of the student whose record is to be deleted :Pooja
: 1 record(s) deletedExplanation:
We used the function mysql.connector.connect to connect the MySQL Database. This function
accepts the required parameters: host, database, user and password. Ifa connection is successfully
established, it will return the connection object.
+ Then we created the parameterized SQL query. In this query, we are using one placeholder,
+ Next, we used the prepared statement to accept user input using a placeholder, ‘c., we put
one placeholder in delete statement for name" column.
+ We then added this one column value in the input tuple in sequential order and passed SQL,
delete query and input tuple with name as ‘nm’ to cursorexccute() function.
+ Inthe end, we commit our changes to the database using connection.commit()
+ We placed all our code in the try-except block to catch exceptions, if any.
Practical Implementation-20
‘To delete the record of a student on the ba:
method.
of name fetched from the user using {} and format()
-7Useis/preet/AppData/Local/Programs/Python/Python37-32/prog del
| Fle Cat Format Ron Optont Window Hep —
fEXecuting deletion at run time using () and format () method
mport mysql.connector
dbl » mysql-Gonnector .connect (host:
mycursor = db1.cursor ()
nm=input ("Enter nane of the student whose record is to be deleted
fPreparing SQL statement to delete records as per given condition
query ="delete from student WHERE name="()'", format (nm)
mycursor-execute (query)
print ("record deleted")
dbl commit ()
dbl. close ()
[]>>>
RESTART: C:/Users/preeti /Appbata/Local/Programs/Python/Python37-32
||n-runtimei .py
|JEnter name of the student whose record is to be deleted :rinku
||record deleted
8.8 CLOSING CURSOR AND CONNECTION
Since the database can keep open only a limited number of connections at a time, we must close
the connection using cursorobject.close(). For example,
cursor.close() or mycursor.close()
This method closes the cursor using cursor object which resets all results and we cannot execute
any SQL statement.
We can disconnect from the database after performing all operations by explicitly calling close()
method along with database object. For example,
conn.close ()pcnATiONt ON A TABLE I A MiraHELL
progeann
wt io the pr psn SOF perfor tilt all the cyeraticans on a table ‘student’ thetragpe # Tote
et wong
f
tnety
Mihi Ch, Ah peranty
FA Rice
onitiatal)
sy enedinee A
efits
niit nein me 5
Cay
furatit
RPV MIM
Ate YOR LOPLYE TALE
onan ti paeeenin (aa EY
(neni cain te teen 2a
dat wet
CO aye
tn Ph
Coa = GatAten
wyatt
Barnet
acerca ate
oot patntatatyt
Fag wpe senannt
ey oe
tye UES AMAT LIANE IE
Coen et -
A nrmah wat BD
ewe ty
T
aitetats
OL myers rant .
pg ina tt PAEMEAAS
Cow = tava) ce
OE casi term eratntl, wate samen! Ti
Cnet sien 2B)
Vea Loehrer a)
pavewanee tatatate!gpERATIONS ON A TABLE IN A NUTSHELL
cangis the Program for performing all the operations on a table ‘student’ through a menu-
Fess
Von program to denonstrate four major ope a
son PiStube through WVSCL-PyEhon connect vey
Hr, add record")
Print (12: ulate record *)
Brunt (°3; delete record”)
Brunt ('4. display records")
Rrint ("5- Exiting")
Rfbioeeiat (anput ("Enter your chos:
fr choice == 1:
addaata 0)
tit choices= 22
vupdatedataQ)
oii ehoices= 3:
aeidata 0)
elie choices= 4:
fetendata0)
cenit choice == 52
print ("exiting")
break
‘print ("wrong input
Epp you want to con!
yaata(
Se mysql-connector
xypassworde**,database='52"?
‘dp ~ mysql connector connect (host="Localhost™yuser="
Garsor = db.cursor ()
Garsor.execute ("S
fesuits = cursor
for x in results
print (0)
except
Shine (error: unable to fetch data)
:of + FROM student™ }
retchall ()
Seeore mysql connector
Acport VEG! cpuctor. connect (nost="Locslnest!,Usee™' Foor" spassword:
cursor = db-cursor 0)
Cursor Gaecate (TINSERT 1870 student VAL
cursor erecute (_Tyspat ano student YALCES ATEN (0904 oor a5 tL
GarsoesexeeutS [oguseRe iro student VALIES( TING 7250 %
cursor enecute (CJySENT INTO stdent VALUES ("Tink 3900, "S540
‘ab, comait 0.
print (Records added")
jdatapase=!s1")
(onitut 4000, *Setence®,345,"B1, 12127)
Jéce vpdatedata 0 +
SEport Rysql.connector
tay
njocathost" users" root" password
‘ap = mysql .connector .connect (nost=
cursor = db-curs0F ()
SAro™ Gupaate student set stipend
Gdrsor.execate (sal)
print ("Record Updated")
‘Sb. commit 0.
‘except Exception 3 ¢!
print (e)
det dendacaQ :
{apart mysql -connectox
dport myadl cones connect (hosta"socalnest* user" scot, Panevorar’ + yaatabase='s1")
‘cursor = db.cUrs0r()
Sater eke Erm student where nanestRAEU'T
Cursor.execute (sql)
print (Checord Deleted")
‘Sb. commit ()
5000 where nano=" Ritu")Fy Mews .oners
ete en sins
acteaites oF “Hoe
21) for more Lncormat ton.
rython Python)?
Iappoataytocat /Prege
y
1 Staptay Teco
ter your chotcel 1
display records
Pte
‘your chotce 4
Wfooe, science’, 345, "Ht, *22")
(eAnkush', 6000, "Comee?, 44,
(dina, d96e,. tmunan
Le add record
Untate record
aptay records
Encer your choice: 3
Record peleted
record
splay records
exiting
Enter your choice: &
(arkusns, 6000,
Ctineat, 8900,
1 aan rhcora
2] Update record
3 ablete record
© Glaplay records
Sonating
Rater your chotees §
Exiting
R nenonr BYTES
We use MySQL-Connector Python to connect MySQL.
-
vy
mysql.connector.connect() method of MySQL-Connector Python is used with the required parameters to connect
mysat.
MySQl-Connector Python requires Python to be in the system's PATH, Installation fails if it doesn’t find Python.
MySQLdb is an interface for connecting to a MySQL database server from Python. It implements the Python
Database API and is built on top of the MySQL C API.
{In order to put our new connection to good use, we need to create a cursor object. It gives us the ability to have
multiple separate working environments through the same connection to the database.
~Wutine Croce Cuemors MoS
@) Mine comect 5 user trimers)
ii, Wes-oomeccr
SL oreo
soot scomecar SWS
cee wT STEEN (Suse oe ome wit TSE
(iui asereme
ful Conmecor
ii
Gi wines conmane: © set or chiming Te turee oh oows m2 oman?
y) court) (a) e_cure
i) fi) wore iabase Connection is
ce008 established, we a.
: Lweare
i operation on any table means to fetch ao Teady to create tables using executel) method of the created cursor
1m
2 us
ee etchall method to fetch multiple values ful information from the table.
7 one fetches he ner row of aque from a database table,
7 Teused to query 2 table. TY Fesutset.A result set is an object that is returned when 2 cursor object
wweount is 2 read-only attribute and retur
> mer operation nny dtu Mil te number of rows that were affected by an execute() method:
y to update one or in the table.
soiree pacene more records, which are already available in the table.
. qo dis rection, use close() method.
ossecTIVE TYPE QUES TIONS
4, Fillin the blanks.
(a)
methods will r .
pp }eturn only one row from the result set in the form of a tuple containing
(b)
method returns th i
sirthe sa table, result set in the form of tuples containing the records or rows returned
t i
(A : refers to a logical set of records that is fetched from the database.
(a) Asession between the application program and the database is called ...
fe) A seen 18 a Special i ; i
(e) as Pecial control structure that facilitates the row-by-row processing of records in the
(A query is used to check if data has been added to the table or not.
{g) To connect MySQL database .. script is used.
(h) ieee . is a property of cursor object that returns the number of rows allowed from the cursor
so far.
() - package can be imported in place of mysql-connector.
wa isa collection of organized information that can be easily used, managed, updated,
and they are classified according to their organizational approach.
2. State whether the following statements are True or False.
{a) Read operation on any table means to fetch some useful information from the table.
(b) Use fetchall() method to retrieve only one value from a database table.
{c) rowcount is a read-only attribute.
(d) To disconnect database connection, use connect() method.
(e) Update statement is used to insert data into the table.
(f) Aresultset is an object that is returned when a cursor object is used to query 2 table.
(g) After establishing connection, execute() method is used.
{h) fetchone() fetches the next row of a query result set.
(i) DB-API is the standard for Python's database interface.
(i) connect() method does not require any parameters.
3. Multiple Choice Questions (MCQs)
(a) Which connector is used for linking the database with Python code?
(i) MySQL-connector (ii) YesSQU: connector
(iii) Postsat: connector (iv) None of these
{b) To open a connector to Mysql database, which statement is used to connect with mysql?
() connector (ii) connect (iil) password (iv) username
(c) Which software is used for coding the Python language?
(i) tdea (ii) IDLE (ili) Python Script (iv) Connector
(4) Which command is used for counting the number of rows in a database?
(i) row (ii) rowcount (iii) count() (iv) row_count
a(hee ee etic AEST sass as SIA SN atiNE aA MaHTD RO nal
ay staan Wy naan far eh Wie eRe
(Ph Fre meconten ob Few epi si es ene a PON Saat
(0) Sete 0p, Raat Lah tocsinereewet 160) OHH AF Hee
Wh A Hm match seach tas abe Maing fo Staton
a eee 1 ewe ny, Sewer a) Sten
(161) Ser hee tae am Kot minty F6: 2b itiinin
100 Monet AT eatin 1 tomeeeente (On) om Fhe
1) Pom eereseime een top seston Sb etemtedte te
4 seine ty way A008) sitive 0 ee oF Ane
(UMP esr east Ho testing a Abe asuricnntnnn tt
1 rr tose an, eo (a) san gun (et) sets
16) WOR VE Masoetenes of maneeomoN on te geen Mn wfbunan mantener e-eninth te acnatat ely Mer or aye
11 eer anereemenit 1) ern
(HD eer te_serarmerendt (0 rire te earner)
UD hears y thee ceyermes etorermmen: ie sient nepeneh
wie .
1, ween coarraene UN eropunnce snared) (arr ngmae ater) (CH) on qe ouarcaney
SOQ WR Qe 99K
1. N10 Me ie ame eras an ORIN: aH FT AW snr wernt
Alea nyo einem me amuses
FB witha ith sagellecmtens oF aie sommes?
Ae, sominnune) Masta Me ine a saan a weUaGh & eaMRMAKI INT AS MAWTEGL fatatbeine using YPN merge
A vaag ie ie aus oF epmeane!it
Ao, he mate af encanto a LITE emus muh a Chore, mers, Galanin, Ewe ah, aon wits
Peter onesie
A meat are the Seaman WS
Ae MURR ar neNnes Here BATTEN SUIT HITT 8 wie Serge oF Hemet anins er sl ari greogrcHming
nd Mae moan cent penne The Brees wet yarns Sh Sally me sami Me ahaa
Ewan ae ee Dane ean AP Corre wr MAY ing tate Atetaere dn nerennt hee Mahal ti oF
memoars wrwor D8 5
Aen The hace eae te cones AEN REM UR WIE MIYEGH Uistile Wem tersd are
Deen ce Meme seu act rene ame nme pectage Ter Heathens Hinermettiltyy SAYISLE «©
marathon ne
(8 Creane 2 enmmenon a Srtabaoe SIME CMM) ete get nwt grammars earth we
ewe pacomert net Ramhase sare
(8D Creame 9 cree sommes
fret Lenenoe SASL tumry Doere meme Nona mnt af members wth 4 Th
fet erewree ture Sam ornaltne wamiatie met Chasing wore ger) rmeamE,
fe Chae Phar coremeee tien towereud="passwd', db="db")
execure(®
row = CUrSOr. fetch
embers WHERE id = 1")
int (row)
6. What is Python’s database interface known asp
ans. DB-APIIS the standard for Python's databene
of tools used by an Application progra
abase inter
8¢ interface, Database Application Programming Interface is a set
as Database Management System,
™f© communicate with the Operating System or other programs such
7. What does database DB-API include?
. Using Python structure, DB:
ans eepusts ofthe following ston eae ® se4NGard and support for working with databases. The API working
{i) Bring in the API module
) Obtain database connection
(ii) Issue SQL statements
(iv) Close the connection
and then store procedures
8. In the following connection string, identify the elements:
connect( <<1>> 127.001, >
oot", <<3>>_ = admin”
fans. <<1>> host, <<25> user, <<3> passwd :
connect(host= 127.0.0.1, user
‘root’, passwd ‘admin’)
9, Explain the benefits of Python Database Programming.
‘Ans. (i) Programming in Python is considerably simple and efficient as compared to other languages. Likewise,
Database programming is much easier using Python-MySQL connectivity.
iieon daeaoess is portable and the program is also portable, which is an advantage in terms of
portability,
(iii) Python supports SQL cursors.
{iv) It also supports Relational Database Systems.
(v) The API of Python for the database is also compatible with other databases.
(vi) Itis platform-independent.
(ii)
10, How can we implement MySQL Database?
‘Ans. To use MySQL database using Python, we need to first install it on our machine and then type the script given
below to implement MySQL in the program:
import MySQLdb
11, Explain the various database operations one can perform using MySQL-Python connectivity.
‘Ans. There are various operations that can be performed within a Python program. To deal with these statements,
‘one must have a good knowledge of Database programming and SQL.
Database Operations Description
Environment Variables
INSERT This an SQL statement used to create a record into a table.
READ, Fetches useful information from the database.
UPDATE Tis used to update already existing or available record(s).
DELETE itis used to delete records from the database.
ROLLBACK Tt works like “undo” which reverts all the changes that you have made.for example
conn
6, What Is Python’s database interface known
‘pp-APIis the standard for Python's d,
of tools used by an Application progr
as Database Management System,
as?
Ans: atabase interface, Database Application Programming Interface is 2 56°
3m to communicate with the Operating System or other programs such
7, What does database DB-API include?
ns. Using Python structure, OB-API provides standard
consists of the following steps:
{i) Bring in the APL module
{i) Obtain database connection
{ii Issue SAL statements and then store procedures
(iv) Close the connection
port for working, with databases. The API working
8, In the following connection string, identify the elements:
connect( <<1>> = 127.001,
fans, <<1>> host, <<2>> user, <<3> passwd
connect(host= 127.0.0.1, user= ‘root’, passwd= ‘admin’)
= "root", <<3>> = "admin’
‘9, Explain the benefits of Python Database Programming.
fans. (i) Programming in Python is considerably simple and efficient as compared to other languages. Likewise,
Database programming is much easier using Python- MySQL connectivity.
(i) Python database is portable and the program is also portable, which is an advantage in terms of
portability.
(iii) Python supports SQL cursors.
(iv) It also supports Relational Database Systems.
(v) The API of Python for the database is also compatible with other databases,
(vi) Itis platform-independent.
10, How can we implement MySQL Database?
‘Ans. To use MySQL database using Python, we need to first install it on our machine and then type the script given
below to implement MySQL in the program:
import MySOLdb
11, Explain the various database operations one can perform using MySQL-Python connectivity.
Ans. There are various operations that can be performed within a Python program. To deal with these statements,
one must have a good knowledge of Database programming and SQL.
Database Operations Description
Environment Variables
INSERT, Ttis an SQL statement used to create a record into a table.
READ Fetches useful information from the database.
UPDATE itis used to update already existing or available record(s).
DELETE Tt is used to delete records from the database.
ROLLBACK, Ttworks like “undo” which reverts all the changes that you have made.12, Consider the information stored In the table ‘EMP":
a ALEX Music 60000
2 PETER ART 67000
BE JOHNY we 55000
4 RAMBO. PRHE 48000
The following Python code is written to access the records of table *EMP". What will be the output of the
following code:
1 Assume all basic setup related to connection and cursor creatl
query="select * from EMP"
mycursor.execute (query)
results = mycursor. fetchone ()
results = mycursor. fetchone ()
results = mycursor.fetchone ()
d= int (results{31)
print (d*3)
‘Ans. 165000
13, Consider the given code and give the outpul
i
‘cealhost users *roct!
ion Is already done.
TE Byag! coRwector as
Inyean = mys.connect (Rost!
layeursor = aycen.cursor()
NVEUESOE -0x0% ject * fron exp")
laydaca = mycurscr.fetchone ()
ipsint ("otal records fetched s0 far a1
layeata * mycurser..
[ncec = mycursor-rowcount
[print ("Total records fetched so far aretyntec)
Inyeata » mycursor. fetchnany (2)
larec = mycursor.rovcount
otal records fetched so far are7/nrec)
Ans. Total records fetched so far are 1
Total records fetched so far are 2
Total records fetched so far are 4
Consider a database ‘company’ that has a table ‘Emp’ that stores IDs of employees. Write a MySQL-Python
connectivity to retrieve data, one record at a time, for employees with IDs less than 10.
Ans, import MySQLdb as mycon
try:
‘db = mycon. connect (host="localhost", user="root", passwd="",
database="company"
cursor = db.cursor()
sql = "select * from Emp where id < 10"
number_of_rows = cursor.execute (sql)
print (cursor. fetchone()) # fetch the first row only
1 ab.close()
except mycon.DataError as e:
print ("DataError")
print (e)
14,