Interface
Python with
SQL
Databases play a vital role in the
efficient working of an
organization as it store data
permanently. From a construction
firm to a stock exchange, every
organization depends on large
databases.
Python- My SQL connectivity
While designing real-life
applications, certain situations
arise pertaining to store some
important and necessary
information by the user.
Python- My SQL connectivity
The input is fetched from
the user using Python
Interface and is known
as Front End Interface.
Python- My SQL connectivity
While working with Python Interface as
Front End, a database is used by the
application to store a lot of data
permanently which is not directly
accessible to the user. This database is
called Back-End Interface.
Front End –Back End
Installing MySQL Connector
1. In spyder, open anaconda prompt
>>conda install -c anaconda mysql-connector-python
python IDLE(if path is not setup), open command
prompt >> cd users\user\Data\Local\Programs \Python37-32\scripts
>>pip install mysql-connector
Why Python
Python is flexible, portable ,easy to learn
and a modifiable (Open Source ) Language.
More efficient and faster compared to
other languages
Portability
Platform independent
Why Python
Supports SQL cursors. Python takes care
of open and closed connections of the
database to avoid further exceptions.
Supports relational database systems.
Python APIs(Application Program
Interface) are compatible with various
databases.
Python – MySQL Database Access
Steps
[Link] packages required for connectivity
[Link] and establish a connection to database
[Link] a cursor object or instance
[Link] Query
[Link] data from the result set
[Link] data as required
Python – MySQL Connectivity
import [Link] as msql Import packages required for
connectivity
con=[Link](host='localhost', Open and establish a connection to
user='root',passwd='student', database
database='jsdb')
cur=[Link]() Create a cursor object or instance
[Link]("select * from emp") Execute Query
rs=[Link]() Extract data from the result set
import [Link] as msql Import packages required for connectivity
con=[Link](host='localhost',user='root', passwd='student',
Open and establish a connection to
database='jsdb') database
if con.is_connected():
cur=[Link]() Create a cursor object or instance
[Link]("select * from emp") Execute Query
rs=[Link]() Extract data from the result set
for row in rs:
for it in row:
print(it, end='\t') Manipulate data as required
else:
print()
[Link]()
else:
print("Error in connection")
import [Link] as cur=[Link]() Create a cursor
object or instance
[Link]("select *
msql Import packages required
for connectivity
Execute Query from emp")
con=[Link](ho rs=[Link]()
st='localhost',user='r for row in rs: Extract data from the
result set
for it in row:
oot', passwd= print(it, end='\t')
'student',database='j else: Manipulate data as
Open and establish a required
sdb') connection to database print()
if con.is_connected(): [Link]()
else:
print("Error in connection")
output
methods
connect()
Establishes a connection to the MySQL
database.
eg: import [Link] as msql
con=[Link]()
Requires parameters:
- host, user,passwd,database
is_connected()
is the function of MySQLConnection
class through which we can verify if
our Python application is connected
to MySQL.
eg.: con.is_connected()
cursor()
The MySQL Cursor object
instantiates objects that can
execute operations such as SQL
statements . Cursor object
interact with the MySQL server.
cursor() contnd…
Eg.: cur=[Link]()
An arbitrary number of cursors can
be created. The cursor is used to
traverse the records from the result
set.
execute()
associated with cursor object is
used to execute the SQL queries
from Python program.
eg. [Link](“ query”)
READ OPERATION
[Link]()
-reads all the records/rows in a result set. If some rows already has
been retrieved, it retrieves the remaining rows from the result set.
[Link]()
A pointer is initialized which points to the first record.
[Link] Eg.:print("ROWS=",[Link])
returns the numbers of records that were affected by the execute()
close()
Clean up the environment by
closing the connection to the SQL
database.
eg,: [Link]()
Python- My SQL
connectivity
Part 2
SQL COMMANDS
1. DDL –Data Definition Language
CREATE TABLE, ALTER TABLE, DROP TABLE
2. DML- Data Manipulation Language
INSERT INTO, DELETE, UPDATE, SELECT
3. DCL/TCL- Data/Transaction Control Language
COMMIT,ROLLBACK, SET AUTOCOMMIT
Transactions(DML) in
python must be
managed by TCL
commands
TCL commands
1. commit()
to save changes/transactions made.
eg. :[Link]()
2. rollback()
mysql>select @@autocommit;
- to discard changes made. shows status autocommit
eg. :[Link]() mode
3. set autocommit =0/1 (0 autocommit is disabled, 1 will enable)
to save the changes automatically. False by default.
eg :[Link]('set autocommit=1')
Create a new database ‘school’
from python to mysql
[Link]("create database if
not exists school")
[Link]("show databases")
Code for creating a database ‘school’
import [Link] as msql for row in cur:
con=[Link](host='localho for it in row:
st',user='root',passwd='student' print(it, end='\t')
,database='jsdb') else:
if con.is_connected(): print()
cur=[Link]() [Link]()
[Link]("create database else:
if not exists school") print("Error in
[Link]("show databases") connection")
To create a table student and
insert 2 records into it
import [Link] as msql
con=[Link](host='localho [Link]("insert into
st',user='root',passwd='student', student values
database='school') ('s101,'Shreya',100)")
if con.is_connected(): [Link]("insert into\
cur=[Link]() student values\
[Link]("use school") ('s102','Maya',98)")
[Link]('create table [Link]()
student\ [Link]()
(id char(4) primary key,\ print("Connection closed")
name varchar(15),\ else:
mark int(3))') print("Error in connection")
import [Link] as msql
con=[Link](host='localhost',user='ro
ot', passwd= 'student',database='school')
if con.is_connected():
cur=[Link]()
[Link]("select * from student")
rs=[Link]() ## rs=[Link]()
OR
## for row in rs:
print(rs) ## for it in row:
[Link]() ## print(it, end='\t')
else: ## else:
## print()
print("Error in connection")
Assignment:
1. Update the mark of student Maya as 95
2. Insert one more Record with your name
as student
3. Delete the record of student Shreya
In table student using python. Write each
Read data from user
using python and insert
into a table:
import [Link] as msql
con=[Link](host='localh
ost',user='root',passwd='studen
t‘,database=‘school') #or [Link]()
before closing
cur=[Link]() connection
[Link]('set autocommit= 1')
print("input id,name and mark of a
student:")
id,name,mark=input().split() #eg 101 Ryan 98
OR
#here name cann’t be more than word id1=input('Enter id: ')
name=input("Enter mark: ")
mark=int(mark) mark=int(input('Enter mark: '))
sql="insert into student values('{}','{}',{})"
[Link]([Link](id,name,mark))
[Link]()
More Practice on connectivity
Connect to MySQL, create and display
the contents of tables:
1 .Dept 5. Fabric
2. Stock 6. Garment
3. Dealers 7. Worker
4. PayLevel
Table Emp
Table: Dept
Deptno Dname Loc
10 Accounting NEW YORK
20 Research DALLAS
30 Sales CHICAGO
40 HR BOSTON
50 Operations Bangalore
Project work must be
completed using
Connectivity.
Thank You