0% found this document useful (0 votes)
9 views

MySQL Connectivity

Uploaded by

randomblaster28
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

MySQL Connectivity

Uploaded by

randomblaster28
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

MySQL Connectivity Class XII

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.

import mysql.connector as mysql


from tabulate import tabulate
dco=mysql.connect(host='localhost',user='root',password='bikramkwt'
,database='class12')
co=dco.cursor()
#retreives one row from the result set
co.execute('select * from empsal')
row=co.fetchone()
#retreiving remaining rows from the result set
emptable1=co.fetchmany(6)
Page 1 of 7
MySQL Connectivity Class XII
#invoking fetchone() after end of result set
emptable2=co.fetchone()
#select query produces empty set
co.execute('select * from empsal where name="ABCD WXYZ"')
emptable3=co.fetchone()
print(row)
print(tabulate(emptable1, tablefmt='plain'))
print(emptable2) #Displays None
print(emptable3) #Displays None

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
None
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 ([]).

import mysql.connector as mysql


from tabulate import tabulate
dco=mysql.connect(host='localhost',user='root',password='bikramkwt'
,database='class12')
co=dco.cursor()
#retreives one row by default from the result set
co.execute('select * from empsal')
row=co.fetchmany()
#retreives remaining rows from the result set
emptable1=co.fetchmany(6)
#invoking fetchmany() after end of result set
emptable2=co.fetchmany()
#select query produces empty set
co.execute('select * from empsal where name="ABCD WXYZ"')
emptable3=co.fetchmany(7)
print(row)
print(tabulate(emptable1, tablefmt='plain'))
print(emptable2) #Displays empty list
print(emptable3) #Displays 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 ([]).

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()
#invoking fetchall() after end of result set
Emptable2=co.fetchall()
#select query produces empty set
co.execute('select * from empsal where name="ABCD WXYZ"')
emptable3=co.fetchall()
print(tabulate(emptable1, tablefmt='plain'))
print(emptable2) #Displays empty list
print(emptable3) #Displays empty list

Execution of the above program produces following output:


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
[]
[]

• 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'))

Execution of the above program produces following output:


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
----------------------------------------------
Result Set Showing Updated Table
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

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.

import mysql.connector as mysql


from tabulate import tabulate
dco=mysql.connect(host='localhost',user='root',password='bikramkwt'
,database='class12')
co=dco.cursor()
#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')
dco.commit()
emptable2=co.fetchall()
print('Result Set Showing Updated Table')
print(tabulate(emptable2, tablefmt='plain'))

Execution of the above program produces following output:


Result Set Showing Updated Table
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

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

b) Add following rows in the teacher table:


CODE NAME GENDER DEPT NOP
2011 MR. JATIN MALE MATHEMATICS 27
2013 MR. PRANAV MALE CHEMISTRY 26
2015 MS. GEETA FEMALE PHYSICS 27
2017 MS. MARIA FEMALE CHEMISTRY 24
2019 MS. PARUL FEMALE MATHEMATICS 25
2012 MR. ADITYA MALE PHYSICS 24
2014 MS. ROOPA FEMALE PHYSICS 25
2016 MS. MALATI FALE MATHEMATICS 24
2018 MR. DEEPAK MALE CHEMISTRY 27
2020 MR. KUNAL MALE PHYSICS 27

c) Write a Python function to execute following query (with menu):


i) Display the teacher table on the screen
ii) Display the teacher table sorted in descending order of NOP
iii) Input CODE and search for CODE in the teacher table. If inputted CODE does not exist, then
display an appropriate message.
iv) Input DEPT and displays all the teacher's details for the inputted DEPT. If inputted DEPT
does not exist, then display an appropriate message.
v) Display number teachers DEPT-wise
vi) Display number teachers GENDER-wise

d) Write a Python function to add following columns in the teacher table:


DESIG CHAR (3) DESIG Designation
BONUS FLOAT BONUS Diwali bonus

e) Write a Python function to edit column DESIG as:


CODE NAME DESIG
2011 MR. JATIN TGT
2013 MR. PRANAV TGT
2015 MS. GEETA PGT
2017 MS. MARIA HOD
2019 MS. PARUL PGT
2012 MR. ADITYA HOD
2014 MS. ROOPA PGT
2016 MS. MALATI HOD
2018 MR. DEEPAK TGT
2020 MR. KUNAL TGT
To edit column BONUS:
DESIG HOD PGT TGT
BONUS 2000 1750 1500

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

You might also like