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

Notes Database Connectivity 2022

Uploaded by

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

Notes Database Connectivity 2022

Uploaded by

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

Interface of Python with MySql

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

Why connecting Python with MySQL?


To design real life applications, we need to manipulate the data which is stored in database(s).
Therefore the frontend software(Python) must be able to connect with back end software
(MySql).
In order to connect a database from Python, we need to install a library that provides the
connectivity functionality. Here with Python IDLE we will use a library mysql-connector.

Note: This library must be installed into python. There are certain steps involved to install
mysql-connector with Python.

How to check the Mysql-connector library is installed or not?


In interactive mode of Python type
>>> import mysql.connector
If the response is no error; it means, it is installed o.w. we need to install the library
mysql.connector first.

Note: Here we assume that the mysql.connector is already installed.

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.

Step-1 Start Python


Start Python by starting the Python IDLE.

Step-2 Import mysql.connector Package:


import mysql.connector
or
import mysql.connector as con
Pl. note here con is name of identifier given to the package mysql.connector

Step-3 Open a Connection to MySql database:


To establish a connection with MySql database we use a method connect() of
mysql.connector package.
The connect() method creates a connection to the MYSQL server and returns a MySql
connection object.
Syntax of connect() method:
<Connectionobject>=mysql.connector.connect(host=<localhost>,
user=<username>, passwd=<password>, database=<database name>)

Here the method connect() takes four parameters,

host- is the host name localhost


user- is the user name on MySql root
passwd-name is the database server hostname or IP address tiger
database- is optional which provides the database name of a MySql database. sanjay

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>

How to check the current host and the user name?


Type the command
mysql>select current_user();

What is a Database connection object?


A database Connection object controls the connection to the database. It represents a unique
session with a database connected from within the script/program.

How to check the connection established or not?


 By default, if the connection is successfully established no errors are reported by Python. If
not connected then Python will give some errors.
 If successfully connected then the value of Connection object (MyCon in above case) will
have a value true. We can check it …
import mysql.connector
DbConObj=mysql.connector.connect(host="localhost",user="root",
passwd="tiger",database="sanjay")
if DbConObj.is_connected():
print(“Successful connected to MySql database………”)
else:
print(“Oh!!! Something went wrong, can’t connect to MySql
database…… ”)

4. Step-4 Create a cursor Instance:


After having successful connection with MySql database, the script/program sends request (in
form of a query) to the server, after getting the query executed, a set of rows called the result
set, is sent over the connection to us. But what if we want to access the retrieved data one row

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()

5. Step-5 Execute SQL Query:


After creating the cursor, to execute the query we can use execute() function. execute()
function is called with the cursor object and take
Syntax:
<cursor object>.execute(<“SQL query String”>)
For example
MyCursor=DbConObj.cursor()
Mycursor.execute(“show tables”)
The retrieved records will be stored in the object named cursor

6. Step-6 Extract data from Resultset


To extract records from the cursor object we use fetch…..() function.
Syntax :
<data>=<cursor object>.fetch…..()
Here the variable will store the records(tuple).

Types of fetch functions are fetchall(), fetchmany(), fetchone().


1. <data>=Mycursor.fetchall():
This will return all the records from the database using the query. The result will be
stored in the variable data.
Example:
import mysql.connector #2
MyConObj=mysql.connector.connect(host="localhost",user="roo
t",passwd="tiger",database="sanjay") #3
MyCursor=MyConObj.cursor()#4

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

7. Clean up the environment:


After the work. If you wanted to close the connection, we can follow the command given
below:
<Connection object>.close()
e.g DbConObj.close()

Understanding the whole process again:

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

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>%s and
Manufacturer='%s'"%(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'))

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:

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

Show the structure of a table in database


Q4. WAP to describe the structure 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"""
""" Program to show all the records of a table in a database
using the database\
MYSql connectivity"""

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

Performing Insert, Update, Delete queries

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)

# check table created or not


MyCursor.execute("DESC EMPL")
data=MyCursor.fetchall()
for i in data:
print(i)
MyConObj.close()

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

Inserting records in the table

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

You might also like