Interface Python
with SQL
9.1 INTRODUCTION
Databases play a vital role in the efficient working of an organization, From a construction firm to
astock exchange, every organization depends on large databases, These are essentially collections
of tables 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
1 stored data, Additionally, these databases
and also to create and exploit the relationship betwe:
support database normalization rules for avoiding redundancy of data, Python programming
language has powerful features for database programming, Python supports various databases
like MySQL, Oracle, Sybase, PostgreSQL, ete, 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-APL is a
widely-used module that provides a Database Application Programming Interface. It is a
standard for database interfaces, Database Application Programming Interface is a set of tools
used by an Application program to communicate with the Operating System or other programs
such as Database Management System. These APIs are implemented by calling functions in the
programs which provide linkage to the required prog)
m to perform a task
Most Python database interfaces adhere to this standard.
(We can choose the right database for our application, Python Database API supports a wide range
of database servers such as—
+ GadFly
+ mSQL.
+ MySQL
+ PostgreSQL
* Microsoft SQL Server 2000
+ Informix
+ Interbase
* Oracle
sybase9.2 PYTHON-MySQL CONNECTIVITY
While designing real-life applications, certain situations arise pertaining to Storing some
important and necessary information by the user. Usually, the data inputted by the user along
with the generated output is displayed but not stored because all program execution takes place
inside the RAM which is a temporary memory and as soon as we close the form, its contents
(form input and generated output) get erased. They can't be retrieved since they are not saved
ona hard disk (or any secondary storage device). Thus, when the application is executed the nex,
time, it requires a new set of inputs from the user. This limitation can be overcome by sending
the output generated and saving the input fetched from the user in a database created at the
back-end of the application. The input is fetched from the user using Python Interface. This is
termed as the Front End Interface of the application.
MySQL
Python
Fig. 9.1: Front-end (Python) and Back-end (MySQL)
Database (The Back-End)
While working with an application, it is required to save data permanently on some secondary
storage device, which is usually the hard disk, so that stored data could be used for future
reference, modification, deletion and retrieval. An application usually stores a lot of data in the
form of a database which is not directly accessible to the user. This database is used by the
application to give suitable response to the user. This database is called Back-End Database.
In Chapter 8, 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
so 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.
9.3 WHY PYTHON
(ython is a exible, portable, easy to learn and modifiable language)So, we are integrating MySQL
with Python interface for executing any databa
for programming database applications are:
¢ applications. The various reasons to use Python
+ Programming in Python is arguably more efficient and faster as compared to other languages
* Python is known for its portability.
+ Itis platform-independent.
i —python supports SQL cursor:
In many programming lange
and closed connections of the database to avoid further exceptions and errors, In Python
these connections z
ges, the application developer needs to take care of the open
re taken care of
python supports relational database systems,
python database APIs are compatible with various databases, so it is very easy to migrate and
port database application interfaces
q.4 INSTALLING MySQL-CONNECTOR
qo establish connectivity between Python and MySQL, we require
pis. We must download a separate DB-API module for each database we need to access.
‘The DB-API provides a minimal standard for working with databases using Python structures
and syntax wherever possible. This API includes the following:
+ Importing the API module
+ Acquiring a connection with the database
« Issuing SQL statements and stored procedures
+ Closing the connection
ed to install a connector
Our ultimate goal is to connect Python with MySQL. To do this, we n
Steps to install the connector and connect it to Python are explained below
Step 1: To connect Python to MySQL, we have to install mysql-connector using ‘pip’ command
on the command prompt (cmd).
Command Prompt
NEN IreCEN tre Biot
eee TT ICLy
Se
preeti\ippData\bocal\Prograne\Pythen>ed Python 37-32
yeten cannot Find the path specified.
preeti\appData\Local\Prograns\Pythoned Python3?-32
CN Nr RTE Nee Sry
ON a eres)
Note:
}o ensure that mysql-connector is installed in the same folder as Python and takes the
path as—
cd C:\User
2\ScripStep 2: Once you have set the path, type the command as
f ' mysey t
or
~ Command Prompt
CES EN ee err errs
ers\preeti\AppData\Local\Prograns>ed Python
et iAppData\Local\Prograns\Python>ed Python 37-32
CIUGLSTL MS Tanr aint eet ate be
SPRUE COP NECN Sb ee kar
£4\AppData\Local\Prograns\Python\Python3?-322ed Scripts
FEO Nc ee
etre
sateen rrr MIT Me Ie aster eT
RRRRLERCATE RY re atte Beet er Oe ac RSE
; preearein
eevee errs cerry Srey
Een erin ne TL Ce bi CART eet tt Shane oy
esfully installed nysql-connector-2-1.6
STN TSCTTL St CRM ee hen e A e CRC EEOL
ider upgrading via the ‘python -n pip install ~-upgrade pip’ conn)
SUsers\preeti\AppData\Local\Prognans \Pyt hon\Puthon32-32\Seripts >
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
> mysql.connector |
>
vy
y
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
> 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 |+ S — - 7
Let
g.a.t Mysttdb
wysQldb is an interface for conn
cting to a MySQL database server from Python
jrimplements the Python Database API and is built on top of the MySQL € API
What is 2
Cursor?
What is
( connection?
Fig. 9.2: Components of MySQLdb
Python-MySQL Database Access
MySQLdb is the Python interface to work with MySQL databases. It mu
work with any MySQL database. To import MySQL for Python 3.x, firs
needs to be installed as follows (assuming Python is already installed with pip and its path
included for Windows 8 or 10):
st be imported in Python to
t the module MySQLclient
» 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:
C:\>Python
* Import MySQLdb in Python shell
>>> import MySQLdb
If the above command produces the following result, it means MySQLdb module is not installed
Se ne)
Pees on OE AC
aed
aber ius Tice ee
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/mysalpython
pT 5 “LATEThis 1s followed by establishing connection
and creating objects. for
Learning Tip: Connector for Python—
Interacting with Python on Microsoft Windows
MySQL using Python. ‘Therefore T
conneetor installation, which we have discussed
in the previous section (9.4) is re
Installing Connectot/
ax! managing ll your MySQ! products, Incuding
3 ith MySQL. Installer is the
MySQL Connector/Python, with
recommended approach. It handles all requirements
and prerequisites, configurations and upgrades.
mys
pcommended
lor use
One more thing to be taken into account is that before actually implementing SQL commands
through Python interface, we ean check for the mysql client program which is running at the
back-end of the program. To check for MySQL user; about which sometimes we are not aware of
the following command can be executed on MySQl. prompt
mysql>sei urtent user (3
This command shall display the username which is running on MySQL client program:
rai Files 86) MYSOLNySai Server 8 baal |
SC ae een a
9.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 datab:
Note:
ase, which is MySQL in our case.
ing for MySQL should be correct. We
as password for all implementations connectivity,
Ensure that the username and password you are ent
have used “root” as username and blank (“")
Practical Implementation-1
To establish a connection between MySQLdb and Python:
Create the first program in Python script mode for est.
script file in Python, type the following script and run it
‘ablishing this connection. Open a new
ie Kat forst_fon_ Opes Widew Hep
import mysql .connector
Jaya = mysql .connector. connect (host="1oca i
Print (mya)
»passwde"")irene output as shown below is obtained, this signifies that the connection has been successfully
established.
Users /preets /appbata /Local /Progeans/Python/Python?7~22/
prog mysql pytnt-py 7 a
Faysdi-conaector:connection.mysauconnection object at 0102288470>
We will now understand the above commands in detail.
The first statement is to import mysql.connector into your script, which has already been installed
on your system. The next statement involves the creation of a connection object ‘mydb’ once the
connectivity gets established through localhost for MySQL with username as ‘root’ and password as
**(blank) in our case.
Once this statement is executed successfully, mydb connection object is created and the message
«mysql .connector . connection .MySQLConnection obje
gets displayed, else error message is displayed
_CTM: The connect() method creates a connection to the MySQL server and returns a MySQL Connection
9.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
any data manipulation query to database, it is executed and the result set (set of records) is sent
over 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 helps us perform this task. Cursor stores
all the data as a temporary container of returned data and allows traversal so that we can 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
multiple 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
command 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 by executing the ‘cursor’ function of our database object.
Establishing the connection with MySQL database requires the following steps to be executed
(Fig. 9.3):
1. Use mysql.connector.connect() method of MySQL.Connector Python with required parameters
such as host name, username, password and name of the database to connect to MySQL.
2. Usethe connection object returned by a connect() method to create a cursor object to perform
Database Operations.
Use/type the cursor.execute() to execute SQL queries from Python,abase connection
4. Close the Cursor object using a cursor.close() and MySQi
connection.close() after your work gets completed
5. Catch Exception if any that may occur dur ing this process.
een eeees Pree
Python DB | Python DB API v2.9
AP
2
Y
ysQi
Connector £4
Python | : < |
, oo 6 BEL
“Sa”
Fig. 9.3: Python: MySQL Database Con
Arguments required for connecting MySQL database with Python
QL Server. The
~ Username: This is the username that you use to work with My
username for the MySQL database is “root”,
~ Password: Password is given by the user at the time of installing the mysql databa
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 r
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 establish
we are using a Database named ‘school’ which we will be creating in the upcoming s:
9.7 CREATING A DATABASE
Once the connection gets established, our next step is to create the ne
MySQL through Python. Before creating this database, it is advisable to check whether
database already exists or not. This is done by typing the command—
databas
As is evident from the above screenshot, no database named ‘school’ exists. So, we w
create a database named ‘school’,
aentation-2
sycat maple
sqoersate a new database ‘schoo! in MySQU. through Python
ig is done by typing the command “CREATE DATABAS
the connection and creation of cursor object, In our example, it will be
scREATE DATABASE school”
Database name>" after establishing,
ew file created using Python script mode
inn
#70 create a new database "ach
nport mysql .connector
Imyct = mysql.connector «connect thost=
fayeursor = mydd.cursor ()
Jaycursor-execute ("\HrATt: pxvanAse senool")
Mhostyusereeort" pasawae")
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 ‘school’ by typing SHOW DATABASE!
in MySQL prompt. The screenshot given below shows that database ‘school’ exists.
; command
renee eccan a
aa i
ato i
test H
can) i
oe
|
|
on/eython37~22/proq. sqlpyth py
(Understanding the Python MySQL Database Connection Program
—* import mysql.connector
+ This line imports the MySQL Connector Python module in your program so you can use
this modules API to connect MySQL.
In case the connection fails, import error shall be displayed—
from mysql.connector import Error
+ (mysql-connector Error object is used to show us an er
databases or if any other database error occurs while working with the database.
Example: ER_ACCESS.DENIED_ERROR when username or password is wrong.
when we fail to connect
nysq) connector. connect ()
« [Using this function, we can connect the MySQL. Database; this funetion accepts four
required parameters: Host, Database, User and Password that we have already
discussed.=—
we onnect ()
command of
MySQL in Python.
If no error is displayed, this means the table has been successfully created and can be verified
by using dese command, ie,, desc student; in MySQL prompt which shall display
the structure of the table student in MySQL
New = Sow Tet
SSmrennan
ata
ErISGE i con
Eco Lon
This can also be done directly from Python shell by typing the script given in Practical
Implementation-5.
2\
ie (at Temat_ tan Opens Ynaen Hep
#o check wielher the cteated table exists In
MySOL using Python Inter face
Sport mysql connector
faydb = mysql .connector. connect (host:
mycursor = mydb. cursor ()
MYCUTSOF -execute(*sio% AULA")
for x in mycurso:
Print (x)
In the above program, SHOW TABLES command in SQL is executed using the cursor object
“mycursor’ in Python script. This shall display all the tables present inside the database school
by using for loop for traversing all the tables present inside it and, hence, the output is obtained
as shown below.
/Users/preeti /Appbata/Local/P
rograms /Python/Python37-32/prog_sqipyth2.
Py
Cstudent',
Similarly, we can implement any DDL (Data Definition Language) commands in MySQL using
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.
Practical Implementation-6
To add a new column ‘marks’ in the student table,
Fle_4t_Femat Pun Optons Window Hep
#70 modify table student (adding
MySQL using Python Interface
import: mysql.connector
database" school")
Inycursor-execute("Alter table student’ add (marks int (2))") |
If no error is displayed and the cursor in the front of Python shell starts blinking, it indicates
that the structure of the table student has been successfully modified. This can be verified in
MySQL by using ‘DESC STUDENT,’ and also using Python shell as we will take up in Practical
Implementation-7.oo
tical Implementation-7
jo view the modified structure of student table using Python seript.
Tie tot toot fon Open Wir Hep
WT view Ue moditied structure of table atu
‘Mysal: using Python Intecface
Inport mysql -connector
Jmyd> = mysql -connector .comnect (host
passwde",\)
Satabasen"set
' Jnycursor = myap.cursor ()
Imycursor.execute ("ies stunt")
for x in myeursor:
print (x)
Upon the execution of the above script, the following output shall be displayed as shown in the
| screenshot given below.
RESTART: c:/Users/preeti/mppoata/tocal/erograns/
python/bython3-32/prog. moulpyth3Py |
(iroiino', ine)", "Wry RE", one, *)
vane, Wwarenar(15)'y vfs", 8, nono, *)
Gages," sine ayy ¥eS", ty None, I
Geity!, enaecoy', tees! "none, 1)
Cmarks!, Ine), YES") +) none, 7)
{ As shown in the output displayed, the structure of the table gets displayed in the form of tuple
| of strings.
{ Our next step is to populate this table, ie, insert a record into the table student using
INSERT INTO command through Python Interface.
Inserting Records into Student Table.
After the table student has been successfully created and altered, we will add records to it using
the popular SQL-DML (Data Manipulation Language) command INSERT INTO using Python shell.
Practical Implementation-8
To insert a record into the table student using Python Interface.
#7 insert a new record into table avuder
ays using eython Interface
tabs itne + mysql connector |
¥ ampor? mysql. : |
" mys = myogl connector connect (host “
x i wilvot _ passa
~ Satabasi ”
Imycursor = mydb-cursor 0) uur cata ,
Mefcurser.exetuter" intext 1070 student VRIES, "Taxnn
nya commit ()
pein imyeursor -roNcount, “Record Insexted")
nesTaRr: c:/ser9/preeti /AppData/Local/
paegrans eython/byehon37-32/Breg_mysqlpy
E527 urtadWe can verity whether this record has been
Ctra ee
een
nysq>
+ The cursorrowcount is the property of cursor abject that is used in the given prog
ber of records inserted which is 1 in our case since we
only one record into the student t
shall return the numb
ave inse
able.
Id be enclosed in single quotes
+ For storing String data type values, all the string values should be enclosed in
We can insert multiple records also at the same instance through Python
Practical Implem
ntation
To insert multiple records into the table student through Python interface,
BySql cot
Imya> = mysql -connec
Or
BD romectgy Cites Appa oa ProganePyboey Ron sicomest 9 380 -
Fie Eat Format Rin Options Winsow Help Hf in _
pagers soo: passa, databases ,
nya. commt ()ATE operations are executed in the same way we execute SELECT query using execute().
i meeeves we must remember ‘one thing: after executing insert or update query, we must commit our query
joni tion object with commit().
or example (if our connection object name is mycon)
{ gycon-commit (
sis statement is required to make changes in database permanently, otherwise no changes are made
go the table.
cagetnods to Manage MySQL Database Transactions in Python
achon MySQL-Connector provides the following methods to manage database transactions
(Fig 94).
= commit: MySQLConnection.commit() method sends a COMMIT statement to the MySQL
server, committing the current transaction.
4 rollback: MySQLConnection.rollback() reverts the changes made by the current transaction,
+ autocommit: MySQLConnection.autocommit value can be assigned as True or False to enable
or disable the auto-commit feature of MySQL. By default, its value is False.
Transaction j t
(Quey1, |
Query2
meen | owes TI
Fig. 9.4: Python-MySQL transaction management using commit
> Syntax of commit() method
Once a program has completed executing the query with your changes and you want to commit
the changes to the database, then you need to call commit() method on MySQL connection
object as follows:
connection. comm
& Syntax of rollback() method
When one of the transactions fails to execute and you want to revert or undo all your changes,
then you need to call a rollback method of MySQL. connection object as follows:
KO
connection. rol ibac
‘That was all about transaction handling using Python-SQL connectivity.
In Practical Implementation-9, after multiple records have been inserted into the table student,
itis checked using SELECT statement in SQL. This can be accomplished in Python as well
2I CRUP- Create ead 60! t Pe
practical tnplementation-10
To display all the re
rds of student table using Python shell
“yet! B¥SqL.coonector
mya = mysql -connector .connect (ho:
tnost" Af
r=" at A
asswd="", \
databases.
IRycursor mydb.cursor ()
JAYSUESOE exeCUte CS ess sry senany
Inyrecords = mycursor. tetchall)
(or x in ayrecordss
Prine ta)
Tae at Sh Omg. tars Wndew Hey :
RESTART: C:\Usera\proet \appbata\ local \Program
s\Python\eython37-32\prog_mysqipythé.PY
(, Tarun', 23, ‘Murbai"; 398)
(2, "Pooja’; 23, "chail', 390)
G3) tradhika', 18, ‘Shimla’, 380) f
(4, ‘sonia’, 24, teoa", 300)
(5, "Vinay", 25, "Pune", 410)
(20, ‘snaurya’,'15, "beini", 345)
In the above program, we have used SELECT statement along with fetchall() function. This
function is used to read and display all the records as tuples from the table student.
AEAD Operation
(READ Operation on any database means to fetch some useful information from the database |
+ nce our database connection is established, we are ready to make a query into this database.
(We can either use fetchone() method to fetch single record)or(fetchall() method to fetch
multiple values from a database table. )
+ (fetchone(): It fetches the next row of a query result setA result set is an object that is
returned when a cursor object is used to query a table.
+ fetchall():it fetches all the rows in a result set and returns a list of tuples. If some rows have
already been extracted from the result set, then it retrieves the remaining rows from the
result set. If no more rows are available, it returns an empty list)
+ fetchmany(size)/It fetches the specified number of rows (as a list of tuples) from the result
set. The default size is 1; if there are no rows in resultset, [] is returned.)
+ ‘rowcount: This is a read-only attribute and returns the number of rows that were affected by
an execute() method.) “‘U} #3 rel @ 0)
Using fetchall() method, all the records retrieved from the table student shall get stored in the
object ‘myrecords’ which we can display one by one using for loop.
; Selection using WHERE clause
We can retrieve selected records from the table using WHERE clause in Python shell also in the same
manner as is done in MySQL.
tion-11
Sp ractic ‘al Implement}
To implement WHERE clause using Python interface.
This is to be implemented using MySQL Select..Where statement in Python script as shown in
the given code:Hiapleeenting SRLECT sial sain
mysql connector
Jaya = mysql -connector connect (hoat=" Loc lti sts
uuseresro
passat”, \
Aatabase= ,
Jaycursor = mydb.cursor()
fayeuesor-execute("n loc! saps, ays, mark tw
fayrecerds = nycursor. fetchall ()
Tor x in myrecords
print (x) :
not coal
Delhi’, ‘e., to fetch the records of all the students who
In the WHERE clause, we have used city:
are staying in ‘Dethi’ city. Since there is only one record in the table that matches with the given
criteria on, it shall be displayed as shown
RESTART: c+/Usera/proeti/AppOata
wherel.py
Tshauryst,
5, 385)
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-12
Deleting records from the table student using Python interface.
ysqh -comector ; |
re = mya connoctor. connect (host s
passw=,\
Jaycursor = nyb.curser'()
fayeursor-executa("h
ya. const 1)
Prine (nyoursor.rowcounty
This can be verified using the statement-SELECT * from student; in MySQL.
ree
Sinn Rpt
Oehag eet
Bo Delhi
As is evident from the above output, the record for roll number 1 has been deleted and, hence,
not displayed.
‘RESTART: C1/Usexs/preet i/appData/i
Soll PY
s*hecord (2) Deleteding Python-SQt
UPDATE Operation on any table
n the table. Oo
The tollowing script updates all the records having Name as ‘Vinay’ Here, we increase
AGE
students with name as "Vinay" to 28 years.
To update the student record using MySQL-Python connectivity
AppDataocabrogiama/Pythee/Python39/09.
nyt = ayagl ‘connector .connect (host \
802 execute (query, data)
vsers/preets/appo
This can be verified by checking the records in MySQL.
TI Ciroaram Files Gas MysauwysaL
Porn
eer
Rae
Perry
Fees
paren)
As shown in the output window above, the age of the student ‘Vinay’ has been updated from 25
to 28 years.
Understanding Python MySQL Parameterized Query Program
We used the function mysql ector.connect () to connect the MySQL Database. This
function accepts the required 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
‘as’ for two columns in a table.
«Next, we put two placeholders in update query, one for “name” column and the other for
“age” column.
means to update one or more records which are already ayaijay
}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
s user data in sequential order of placeholders
cont
«Inthe end, we commit our changes to the database using connection.commit().
practical Implementation- 4
‘To delete the record of a student on the basis of name fetched from the user at run-time.
for at fatter dan Hap
Hexecut ing deletion at
fon the basis of ser
Tispor mysql «connector
Jaoi = mysqi.connector connect (host=" jor tisst
users toot")
passud="",
database=" envi")
input
Inycursor = dbl.cursor()
fam-input Pn dent whose record in to be daleted 2")
#roparing SgL stat ete records as par given
#sq1 ="DELATE FROM student WERE Name = "an') ™
mycursor execute (Pint £4 tent ME
Print (mycursor.rowcount, “iecorii(s) ole!
Sb1-commit ()
loxcept we cs
dbi-rottback() |?2>
Jab1 close () [| Restart: c:\users\preeti \apppata\Local \ Programs \Py
delesqipyth.py
Enter nane of the student whose record is to be deleted :Pooja
\]1 record(s) deleted
Explanation:
We used the function mysql.connector:connect to connect the MySQL Database. This function
accepts the required parameters: host, database, user and password. If a 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, ie., 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 cursorexecute() function
+ In the 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.
9.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 ()9.9 OPERATIONS ON A TABLE IN A NUTSHELL
Following is the program for performing all the operations on a table ‘student’ through a mep
driven program,
eint ¢ tinge
choicesint
choice
adadata()
cholces= 2
updatedata()
choices» 3:
deldatai)
choices= 4:
fetchdatai)
choice == 5:
print (exiting)
BEAME (C*wrong input")
fetcndata()+
Sy mysql.connector |
db = mysql «connector. connect (host="! oetyuserss °, passwords", datane: |
cursor = db.cursor() |
cursor.execute("Se5c7 + sro stusent® ) |
results = cursor. fetchal10. j
pr
print ("esrcr: unable
adddata dy:
erort mysql -connector
eb = nysqi-connector -connect (host=" tocal
cursor = db.cursor()
cursor-execute(”
cursor execute (
cursor execute ("1
cursor ‘execute (
@. commit ()
print (Revers added")
We use Mysat-Connector Python ton”
; > mysql.connector.connect() method of M
Mysau
> MySQL-Connector Py!
‘> Install MySOL-Connector Python using pip command
Sg eate c eeeee (ones ea ercae from Python. it implements the Python
Database AP! and is built on top of the MySQL. ¢ API
ject MySQL.
jySl-Connect
tor Python is used with the required parameters to connect
non requires Python to ben the systems PATH. Installation fas f doesn’t find Python.