Notes Database Connectivity 2022
Notes Database Connectivity 2022
Syllabus
Database Connectivity:
- Interface of Python with an SQL database
- Connecting SQL with Python
- Creating Database connectivity Applications
- Performing Insert, Update, Delete queries
- Display data by using fetchone(), fetchall(), rowcount
Database Connectivity
The Python programming language has powerful features for database programming. Python
supports various databases like MySQL, Oracle, Sybase, PostgreSQL, etc. Python also supports
Data Definition Language (DDL), Data Manipulation Language (DML) and Data Query
Statements. For database programming, the Python DB-API is a widely-used module that
provides a database application programming interface. It is a standard for database interfaces.
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 • Sybase
Note: This library must be installed into python. There are certain steps involved to install
mysql-connector with Python.
1|Page
Steps for creating Database Connectivity Applications:
The below mentioned 7 steps are to be followed to create a database connectivity application.
1. Start Python
2. Import the package required for the database programming
3. Open connection to database
4. Create the cursor instance
5. Execute a query
6. Extract the data from result set.
7. Clean up the environment.
The values of the above said parameters are the values which we will use as per our
configuration.
Example to have connection with a database named sanjay.
import mysql.connector
DbConObj=mysql.connector.connect(host="localhost",user="root",
passwd="tiger",database="sanjay")
2|Page
After successfully executing the above command, Python will have MySql database connection.
The user name is ‘root’, password is ‘tiger’ and the database name is ‘sanjay’.
>>> print(DbConObj)
<mysql.connector.connection.MySQLConnection object at
0x00000240AD2C3148>
3|Page
at a time, so a control structure called database cursor can be created to get access of all the
records retrieved.
Resultset: It refers to a logical set of records that are fetched from the database by executing
an SQL query and made available to the application program.
Database cursor: It is a special control structure that facilitates the row by row processing of
records received (resultset ).
Syntax:
<cursor object> = <Connection object>.cursor()
For example
MyCursor = DbConObj.cursor()
4|Page
MyCursor.execute("SELECT * FROM product") #5
data=MyCursor.fetchall() #5
for i in data:
print(i)
MyConObj.close() #7
Output:
('BS01', 'Bath Soap', 'ABC', Decimal('55'))
('FW05', 'Face Wash', 'ABC', Decimal('45'))
('FW12', 'Face Wash', 'XYZ', Decimal('95'))
('SH06', 'Shampoo', 'XYZ', Decimal('120'))
('TP01', 'Telcom Powder', 'LAK', Decimal('40'))
2. <data>=Mycursor.fetchone():
This will return only one recors from the database using the query and store into data
variable. This is useful when we wanted to fetch one record at a time.
If no more data is left, the data will have a value None.
Exmple:
import mysql.connector
MyConObj=mysql.connector.connect(host="localhost",user="roo
t",passwd="tiger",database="sanjay")
MyCursor=MyConObj.cursor()
MyCursor.execute("SELECT * FROM product")
data=MyCursor.fetchone()
print(data)
Output:
('BS01', 'Bath Soap', 'ABC', Decimal('55'))
3. <data>=Mcursor.fetchmany(n):
This will return n records from the database using the query. The records are stored into
a variable data. If no more records are left then it will return empty tuple.
Example:
import mysql.connector
MyConObj=mysql.connector.connect(host="localhost",user="roo
t",passwd="tiger",database="sanjay")
MyCursor=MyConObj.cursor()
MyCursor.execute("SELECT * FROM product")
data=MyCursor.fetchmany(2)
for i in data:
print(i)
Output:
('BS01', 'Bath Soap', 'ABC', Decimal('55'))
('FW05', 'Face Wash', 'ABC', Decimal('45'))
4. <variable>= <cursor>.rowcount
The rowcount property of cursor object returns the no. of rows retrieved from the
cursor so far.
5|Page
Example:
import mysql.connector
MyConObj=mysql.connector.connect(host="localhost",user="roo
t",passwd="tiger",database="sanjay")
MyCursor=MyConObj.cursor()
MyCursor.execute("SELECT * FROM product")
data=MyCursor.fetchall()
count=MyCursor.rowcount
print("There are ",count,"rows in the table")
for i in data:
print(i)
Output:
There are 5 rows in the table
('BS01', 'Bath Soap', 'ABC', Decimal('55'))
('FW05', 'Face Wash', 'ABC', Decimal('45'))
('FW12', 'Face Wash', 'XYZ', Decimal('95'))
('SH06', 'Shampoo', 'XYZ', Decimal('120'))
('TP01', 'Telcom Powder', 'LAK', Decimal('40'))
PARAMETERIZED QUERIES:
Sometimes we may need to run queries which are based on some parameters or values
that you provide from outside
6|Page
e.g.*** in table product Price is more than 50 and Manufacturer is ‘XYZ’
Select * from product where Price> P ;
such queries are called as the parameterized queries.
(i) Old style : String Templates with % formatting
The string formatting uses the general form : f % V
Here f is a template string and v specifies the value or values (value tuple) to be formatted
using that template.
Example : 1. Price>50
“SELECT * FROM PRODUCT WHERE PRICE>%S”%(50)
import mysql.connector
MyConObj=mysql.connector.connect(host="localhost",user="root",
passwd="tiger",database="sanjay")
MyCursor=MyConObj.cursor()
QUERY="SELECT * FROM PRODUCT WHERE PRICE>%s"%(50)
MyCursor.execute(QUERY)
data=MyCursor.fetchall()
for i in data:
print(i)
MyConObj.close()
Output:
('BS01', 'Bath Soap', 'ABC', Decimal('55'))
('FW12', 'Face Wash', 'XYZ', Decimal('95'))
('SH06', 'Shampoo', 'XYZ', Decimal('120'))
Output:
('FW12', 'Face Wash', 'XYZ', Decimal ('95'))
('SH06', 'Shampoo', 'XYZ', Decimal ('120'))
7|Page
Note: pl. remember that the value for the string field must be given in double or single quote
marks( “ ” or ‘ ‘ )
(ii) New style : String Templates with % formatting
The new style use the format() method of the str type.
It uses {} (place holder) in place of %s and format function.
Example : 1. Price>50
“SELECT * FROM PRODUCT WHERE PRICE>{}”.format(50)
import mysql.connector
MyConObj=mysql.connector.connect(host="localhost",user="root",
passwd="tiger",database="sanjay")
MyCursor=MyConObj.cursor()
QUERY="SELECT * FROM PRODUCT WHERE PRICE>{}".format(50)
MyCursor.execute(QUERY)
data=MyCursor.fetchall()
for i in data:
print(i)
MyConObj.close()
Output:
('BS01', 'Bath Soap', 'ABC', Decimal('55'))
('FW12', 'Face Wash', 'XYZ', Decimal('95'))
('SH06', 'Shampoo', 'XYZ', Decimal('120'))
Example : 2. Price>50 and Manufacturer=’XYZ’
import mysql.connector
MyConObj=mysql.connector.connect(host="localhost",user="root",pa
sswd="tiger",database="sanjay")
MyCursor=MyConObj.cursor()
QUERY="SELECT * FROM PRODUCT WHERE PRICE>{} and
Manufacturer='{}'".format(50,"XYZ")
MyCursor.execute(QUERY)
data=MyCursor.fetchall()
for i in data:
print(i)
MyConObj.close()
Output:
('FW12', 'Face Wash', 'XYZ', Decimal ('95'))
('SH06', 'Shampoo', 'XYZ', Decimal ('120'))
Practical Work:
Showing the list of databases:
P1. WAP to show names of all the database using database Connectivity.
Ans:
8|Page
""" This program simply connects the Python to MYSQL and display
the list of data bases\
and tables in the database File: showdatabases.py"""
import mysql.connector
MyConObj=mysql.connector.connect(host="localhost",user="root",pa
sswd="tiger")
MyCursor=MyConObj.cursor()
MyCursor.execute("SHOW DATABASES")
for x in MyCursor:
print(x)
Output:
RESTART: C:\Users\user\AppData\Local\Programs\Python\Python37-
32\Showdatabases.py
('information_schema',)
('mysql',)
('sanjay',)
Create a database
P2. WAP to create a database using database Connectivity.
Ans:
""" This program simply connects the Python to MYSQL and create
a database\
File: createdatabase.py"""
import mysql.connector
MyConObj=mysql.connector.connect(host="localhost",user="root",pa
sswd="tiger")
MyCursor=MyConObj.cursor()
MyCursor.execute(" CREATE DATABASE TEST")
print("Now Printing the list of the databases.....")
MyCursor.execute("SHOW DATABASES")
for x in MyCursor:
print(x)
Output:
RESTART: C:/Users/user/AppData/Local/Programs/Python/Python37-
32/Createdatabase.py
Now Printing the list of the databases.....
('information_schema',)
('mysql',)
('sanjay',)
('test',)
>>>
Showing the list of tables in a database:
P3. WAP to display the list of tables in the database.
9|Page
""" This program simply connects the Python to MYSQL and dislay
the list of\
tables in the database File: Showtables.py"""
import mysql.connector
MyConObj=mysql.connector.connect(host="localhost",user="root",pa
sswd="tiger")
MyCursor=MyConObj.cursor()
MyCursor.execute("USE SANJAY")
MyCursor.execute("SHOW TABLES")
for x in MyCursor:
print(x)
Output:
RESTART: C:\Users\user\AppData\Local\Programs\Python\Python37-
32\Showdatabases.py
('client',)
('employee',)
('product',)
('test',)
>>>
Show the records of a table in database
Q3. WAP to show all the records of a table in a database using database Connectivity. """
Program to show all the records of a table in a database using the database\
MYSql connectivity"""
import mysql.connector
MyConObj=mysql.connector.connect(host="localhost",user="root",
passwd="tiger",database="sanjay")
MyCursor=MyConObj.cursor()
MyCursor.execute("SELECT * FROM product")
for i in MyCursor:
print(i)
Output:
10 | P a g e
import mysql.connector
MyConObj=mysql.connector.connect(host="localhost",user="root",pa
sswd="tiger",database="sanjay")
MyCursor=MyConObj.cursor()
MyCursor.execute("Desc product")
data=MyCursor.fetchall()
for i in data:
print(i)
MyConObj.close()
Output:
========= RESTART: J:\XII_2020_21\CS 2020-21\Unit_II\
Showrecords.py =========
('P_ID', 'char(4)', 'NO', 'PRI', None, '')
('ProductName', 'char(15)', 'YES', '', None, '')
('Manufacturer', 'char(3)', 'YES', '', None, '')
('Price', 'decimal(3,0)', 'YES', '', None, '')
Before performing Insert, Update and delete operations let us create the table first.
CREATING TABLE:
import mysql.connector
MyConObj=mysql.connector.connect(host="localhost",user="root",pa
sswd="tiger",database="sanjay")
MyCursor=MyConObj.cursor()
STR="create table empl( EMPNO DECIMAL(4) NOT NULL PRIMARY KEY,\
ENAME CHAR(15),\
JOB CHAR(15),\
MGR DECIMAL(4),\
HIREDATE DATE,\
SAL DECIMAL(6,2),\
COMM DECIMAL(6,2),\
DEPTNO DECIMAL(2))"
MyCursor.execute(STR)
Output:
('EMPNO', 'decimal(4,0)', 'NO', 'PRI', None, '')
11 | P a g e
('ENAME', 'char(15)', 'YES', '', None, '')
('JOB', 'char(15)', 'YES', '', None, '')
('MGR', 'decimal(4,0)', 'YES', '', None, '')
('HIREDATE', 'date', 'YES', '', None, '')
('SAL', 'decimal(6,2)', 'YES', '', None, '')
('COMM', 'decimal(6,2)', 'YES', '', None, '')
('DEPTNO', 'decimal(2,0)', 'YES', '', None, '')
import mysql.connector
MyConObj=mysql.connector.connect(host="localhost",user="root",pa
sswd="tiger",database="sanjay")
MyCursor=MyConObj.cursor()
R="INSERT INTO EMPL VALUES(8369,'SMITH','CLERK',8902,'1990-12-
18',800.00,NULL,20)"
MyCursor.execute(R)
R="INSERT INTO EMPL VALUES(8469,'ANYA','SALESMAN',8698,'1991-02-
20',1600,300.00,30)"
MyCursor.execute(R)
R="INSERT INTO EMPL VALUES(8521,'SETH','SALESMAN',8698,'1991-02-
22',1250.00,500.00,30)"
MyCursor.execute(R)
R="INSERT INTO EMPL
VALUES(8566,'MAHADEVAN','MANAGER',8839,'1991-04-
02',2985.00,NULL,20)"
MyCursor.execute(R)
R="INSERT INTO EMPL VALUES(8654,'MOMIN','SALESMAN',8698,'1991-
09-28',1250.00,1400.00,30)"
MyCursor.execute(R)
R="INSERT INTO EMPL VALUES(8698,'BINA','MANAGER',8839,'1991-05-
01',2850.00,NULL,30)"
MyCursor.execute(R)
R="INSERT INTO EMPL VALUES(8839,'AMIR','PRESIDENT',NULL,'1991-
11-18',5000.00,NULL,10)"
MyCursor.execute(R)
R="INSERT INTO EMPL VALUES(8844,'KULDEEP','SALESMAN',8698,'1991-
09-08',1500.00,0.00,30)"
MyCursor.execute(R)
R="INSERT INTO EMPL VALUES(8882,'SHIVANSH','MANAGER',8839,'1991-
06-09',2450.00,NULL,10)"
MyCursor.execute(R)
R="INSERT INTO EMPL VALUES(8886,'ANOOP','CLERK',8888,'1993-01-
12',1100.00,NULL,20)"
MyCursor.execute(R)
R="INSERT INTO EMPL VALUES(8888,'SCOTT','ANALYST',8566,'1992-12-
09',3000.00,NULL,20)"
12 | P a g e
MyCursor.execute(R)
R="INSERT INTO EMPL VALUES(8900,'JATIN','CLERK',8698,'1991-12-
03',3000.00,NULL,20)"
MyCursor.execute(R)
R="INSERT INTO EMPL VALUES(8902,'FAKIR','ANALYST',8566,'1991-12-
03',3000.00,NULL,20)"
MyCursor.execute(R)
R="INSERT INTO EMPL VALUES(8934,'MITA','CLERK',8882,'1992-01-
23',1300.00,NULL,10)"
MyCursor.execute(R)
# check table created or not
MyCursor.execute("SELECT * FROM EMPL")
data=MyCursor.fetchall()
for i in data:
print(i)
MyConObj.close()
Output:
13 | P a g e