Introducti
on
Every application required data to be stored
for future
reference to manipulate data. Today every
Fo exampl reservati syste stores
application
details
rstores for reserving
e, data the
inondatabase seats
mfor and later on
passengers
this purpose
for sending some messages or for printing
tickets
I scho etc.
stude detail ar save fo man reaso
like
n olattendance,
nt s fee collections,
e d r exams,
y ns
report
Pythoncard etc.us to connect all types of
allows
database like
Oracle, SQL Server, MySQL.
In our syllabus we have to understand
how to connect
Python programs with MySQL
Pre-requisite to connect Python w
MySQL
Before we connect python program with
any database
like MySQL we need to build a bridge to
To build this bridge so that data can travel
connect
weboth
Python need
andaMySQL.
connector called
ways
“mysql.connector”.
We ca inst “mysql.conne b usin followi
methon all ctor” y g ng
ds:
At command prompt (Administrator login)
Type “pip install mysql.connector” and press
enter
(internet connection in required)
This connector will work only for MySQL 5.7.3 or
later
Or open OS and Python
“https://dev.mysql.com/downloads/
version
connector/python/”
Connectin MySQL Pyth
g to from on
Once the connector is installed you are
ready to
connect your python program to
MySQL.
The following steps to follow while
connecting your python program with
MySQL
Open python
Import the package required (import
mysql.connector)
Open the connection to database
Create a cursor instance
Execute the query and store it in resultset
Extract data from resultset
Importing
mysql.connector
impo mysql.conn O Import MYSQLdb
rt ector r
O
r
import
mysql.connector
as ms Import MYSQLdb as ms
Here “ms” is an alias, time we can use
so every “ms” in
place of
“mysql.connector”
Open a connection to MySQL
Database
To create connection, connect()
function is used
Its syntax is:
connect(host=<server_name>,user=<us
er_name>,
Here server_name means database
passwd=<password>[,database=<
servername, generally
database>])
it is given as “localhost”
User_name means user by which we connect
with mysql
generally it is given as “root”
Password is the password of user “root”
Database is the name of database whose
data(table) we
want to use
Examp T establi connect wit MyS
le: o sh ion h QL
is_connected() function
returns
true connection is
if established
otherwise false
Tabletowork
(emp)
Creating
Cursor
It is a useful control structure of database
connectivity.
When
resultswe
(sefire a query to
of records) sedatabase, it is
ove th connect i
executed
et t and is nt r e ion n
one
We may want to access data one row at a
go. time, but
query cannot happens as one row at
processing a time,
so cursor in performing this task.
help us Cursor stores
all the data temporary container of
as a returned data
and we can data one row at a time from
Creating Cursor and Quer
Executing y
TO CREATE CURSOR
Cursor_name =
connectionObject.cursor()
For e.g.
mycursor = mycon.cursor()
TO EXECUTE QUERY
t connect
We use execute() function to o ion
send query
Cursor_name.execute(query)
For e.g.
mycursor.execute(„select * from
emp‟)
Exam - Curs
ple or
Output shows cursor is created is fired and stored, but no
and query data is
coming. To fetch data we have functions like fetchall(),
to use fetchone(),
fetchmany() are used
Fetching(extracting) data
from ResultSet
To extract data from cursor following
functions are used:
fetchall() : it will return all the record in
the form of
tuple.
fetchone() : it return one record from the
result set. i.e.
second andfirst timeIf itnowill
so on. morereturn firstit
record
record, nextwill
record time it will return
return
None : it will return n number of
fetchman records. It no
y(n)
rowcount :will return
it will an empty
return numbertuple.
of rows
more
retrieved from
record it so far.
the cursor
Exampl– fetchall
e ()
Exampl2 – fetchall
e ()
Exampl3 – fetchall
e ()
Examp4 fetchon
le : e()
Exampl5:fetchmany(
e n)
Guess the
output
Parameterized
Query
We ca pas values quer t perfor dynam
n lik
searc s w towan t ysearch
o m an employ
ic
h eentere
e t durin
o runti
for y ee an
o to
numb column
other d g me r search y
er
Tvalues.
o Create Parameterized can use
query we
methods various
like: dynam variabl t quer i whic
ic
values are entered. e o y n h
Concatenati
String template with %
ng
formatting functi
String template with {} on
and format
Concatenatvariablwit quer
ing e h y
VINOD KUMAR VERMA, PGT(CS), KV OEF
KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1
String template with %s
formatting
In this we will use %s in place of
method
substit an values
the pasto
th valu fo tha plac
ute d n s e e r t e.
Strintemplawit % formatti
g te h s ng
String template with {}
and format()
In this method in %s will use {}
place
pas of we
valu fo thes placehold and to
format() use
s eswe can
Inside r e er 0,1,2…is values d.
for
optionally give e.g.
{0},{1} but its not we can also
mandatory.
valu throu pass
form functioptionally
w nee no t
es
named
rememb gh at
parameter
th orde {} so
ofonvalu e that
d while
t o
er
inside
{roll}, e r e passing
to pass. For e.g
{name} etc. .
Stri templ wit { an forma
ng ate h } d t()
Stri templ wit { an forma
ng ate h } d t()
VINOD KUMAR VERMA, PGT(CS), KV OEF
KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1
Inserting data in MySQL table
from Python
INSERT and UPDATE operation are
executed in the
same way we execute SELECT query
using
updat execute()
quer w mu com ou quer usin
but
e oney thing
connection tostremember,
eobject with r after
mit y g
executing
commit(). insert or
For e.g. (if our connection nam i myco
object e s n)
mycon.commit()
BEFORE PROGRAM
Examp : inserti dat EXECUTION
le ng a
AFTER PROGRAM
EXECUTION
Examp Updati reco
le: ng rd