MySQL Connectivity
MySQL Connectivity
Python's mysql.connector
Python can be linked with MySQL using several Python packages. One such popular package used to
connect Python with MySQL is mysql.connector-python.
A Python package named mysql.connector-python must be installed first before one can use
mysql.connector. A Python package can be installed by using pip install command. Before pip
command is executed, we have to start command line interface in the following way:
Windows Key+R and type CMD and hit <ENTER>
At the command prompt type pip install mysql.connector-python and hit <ENTER>.
mysql.connector is an interface between Python and MySQL server. To use mysql.connector
in a Python script one has to use the following statement:
import mysql.connector as mysql #import mysql.connector
mysql is an alias for mysql.connector.
After importing mysql.connector, we need to create a database connector object using connect()
function of mysql.connector. A database connector object is created as:
dbconobj=mysql.connect(host, user, password, [database])
#dbconobj=mysql.connector.connect(host, user, password, [database])
will connect Python to MySQL server and creates a connector object dbconobj. This connect()
function has at least three parameters - host, user, password and optional parameter database.
Generally, host is localhost (current computer that is being used, instead of localhost, one can also use
127.0.0.1). Generally, user is root but it could be anything else also, password is the password for
the user (root) and database is the name of the MySQL database. The last parameter (database) is
optional. When invoking the function connect(), all the parameters names are to be included during
the function call. Database connector object is created as:
dco=mysql.connect(host='localhost', user='root', password='123+ABC-
xyz', database='mydb')
After creating the database connector object, one must create a cursor object using database connector
object. A cursor object is created as:
curobj=dco.cursor() will create curobj as a cursor object using database connector object
dco. cursor() is a method of database connector object. MySQL commands will be executed through
the cursor object. Few important methods (functions) of cursor object are listed below:
• curobj.execute() will execute SQL query as a string either single line or multi-line. Unlike
MYSQL, Python's SQL query string does not require terminating semi-colon(;).
• curobj.fetchone() will retrieve one row from a result set after a select query from the current
position of the pointer. fetchone() method returns a tuple. fetchone() method does not have
any parameter. If a select query returns an empty set, then fetchone() method will return None.
Invoking fetchone() method when the pointer is positioned at the end of the result set, will return
None.
• curobj.fetchmany(n=1) will retrieve n rows from a result set after a select query from the
current position of the pointer. fetchmany() method returns a list containing tuple(s). Every row
is stored as a tuple. fetchmany() method has a default parameter, number of rows to be retrieved
from the result set and the default value is one (1). If the value stored in the parameter exceeds number
of rows present in the result set, fetchmany() method will return all the rows present in the result
set. fetchmany() method without any parameter will return one row stored as a list and the list
containing the row as a tuple. If a select query returns an empty set, then fetchall() method will
return an empty list ([]). Invoking fetchall() method when the pointer is positioned at the end of
the result set, will return an empty list ([]).
Page 2 of 7
MySQL Connectivity Class XII
Execution of the above program produces following output:
[(1045, 'DEEPAK JAIN', datetime.date(2010, 7, 2), 80000.0, 99456972)]
1072 ALEX JOHN 2007-04-09 75000 55012016
1032 RITA GUPTA 2010-07-02 80000 66442288
1012 NITU SHARMA 2008-10-15 95000 55123765
1049 ALOKA SINGH 2007-04-09 90000 64192837
1025 RITA GUPTA 2008-10-15 95000 55876534
1017 DEEPAK JAIN 2008-09-03 75000 98283761
[]
[]
• curobj.fetchall() will retrieve all the rows from a result set after a select query from the
current position of the pointer. fetchall() method returns a list containing tuple(s). Every row is
stored as a tuple. fetchall() method does not have any parameter. If a select query returns an
empty set, then fetchall() method will return an empty list ([]). Invoking fetchall() method
when the pointer is positioned at the end of the result set, will return an empty list ([]).
• dco.commit() is needed after a DML commands like INSERT INTO, DELETE FROM and
UPDATE SET to ensure that the table is correctly and physically updated. For INSERT INTO, row
must be physically inserted in the table. For DELETE FROM, row must be physically deleted from
the table. For UPDATE, row must be physically updated in the table. Without using
dco.commit(), the result set will show expected result but MYSQL table will not be updated. That
is, when select command is executed through MySQL command line interface will not display the
updated table. Using dco.commit(), will ensure that the MySQL table is also updated.
Page 3 of 7
MySQL Connectivity Class XII
import mysql.connector as mysql
from tabulate import tabulate
dco=mysql.connect(host='localhost',user='root',password='bikramkwt'
,database='class12')
co=dco.cursor()
co.execute('select * from empsal')
emptable1=co.fetchall()
print(tabulate(emptable1, tablefmt='plain'))
print('-'*46)
#adding a new row
co.execute("insert into empsal values (1020, 'SOFIA KHAN', '2010-10-
28', 95000.0, 68154477)");
#updating a row
co.execute('update empsal set bsal=bsal+5000.0 where empno=1032')
co.execute('select * from empsal')
emptable2=co.fetchall()
print('Result Set Showing Updated Table')
print(tabulate(emptable2, tablefmt='plain'))
But running select query from MySQL prompt produces following result:
mysql> select * from empsal;
+-------+-------------+------------+-------+----------+
| empno | name | doj | bsal | mob |
+-------+-------------+------------+-------+----------+
| 1045 | DEEPAK JAIN | 2010-07-02 | 80000 | 99456972 |
| 1072 | ALEX JOHN | 2007-04-09 | 75000 | 55012016 |
| 1032 | RITA GUPTA | 2010-07-02 | 80000 | 66442288 |
| 1012 | NITU SHARMA | 2008-10-15 | 95000 | 55123765 |
| 1049 | ALOKA SINGH | 2007-04-09 | 90000 | 64192837 |
| 1025 | RITA GUPTA | 2008-10-15 | 95000 | 55876534 |
| 1017 | DEEPAK JAIN | 2008-09-03 | 75000 | 98283761 |
+-------+-------------+------------+-------+----------+
Page 4 of 7
MySQL Connectivity Class XII
It is very clear that the table empsal has not been updated. This is because commit() was not
invoked after the DML commands. Updated Python code is given below by invoking commit()
after the DML commands.
But running select query from MySQL prompt produces following result:
mysql> select * from empsal;
+-------+-------------+------------+-------+----------+
| empno | name | doj | bsal | mob |
+-------+-------------+------------+-------+----------+
| 1045 | DEEPAK JAIN | 2010-07-02 | 80000 | 99456972 |
| 1072 | ALEX JOHN | 2007-04-09 | 75000 | 55012016 |
| 1032 | RITA GUPTA | 2010-07-02 | 85000 | 66442288 |
| 1012 | NITU SHARMA | 2008-10-15 | 95000 | 55123765 |
| 1049 | ALOKA SINGH | 2007-04-09 | 90000 | 64192837 |
| 1025 | RITA GUPTA | 2008-10-15 | 95000 | 55876534 |
| 1017 | DEEPAK JAIN | 2008-09-03 | 75000 | 98283761 |
| 1020 | SOFIA KHAN | 2010-10-28 | 95000 | 68154477 |
+-------+-------------+------------+-------+----------+
The table empsal has not been updated in MySQL server.
• dco.close()will disconnect the connection between MySQL server and the Python created with
the connect() method. This statement (call to close() method) is optional.
Page 5 of 7
MySQL Connectivity Class XII
1. Write a menu driven Python program to do the following:
a) Create a table teacher in the database class12 with following columns:
CODE INT teacher's code
NAME VARCHAR (20) teacher's name
GENDER CHAR (6) gender of the teacher
DEPT VARCHAR (15) department
NOP INT number of periods per week
Page 6 of 7
MySQL Connectivity Class XII
f) Write a Python function to execute following query (with menu):
i) Input CODE and delete the row containing inputted CODE from the teacher table. If inputted
CODE does not exist, then display an appropriate message.
ii) Input NAME and delete the row containing inputted NAME from the teacher table. If inputted
NAME does not exist, then display an appropriate message.
Page 7 of 7