SlideShare a Scribd company logo
INTERF
ACEPYTHONWITH
MYSQL
ConnectingPythonapplication with MySQL
Introduction
 Every application required data to be stored for future
reference to manipulate data. Today every application
storesdata in database for this purpose
 For example, reservation system stores passengers
details for reserving the seats and later on for sending
somemessagesor for printing tickets etc.
 Python allows us to connect all types of database like
Oracle, SQLServer, MySQL.
Pre-requisite to connectPythonwith
MySQL
 Before we connect python program with any database
like MySQL we need to build a bridge to connect
PythonandMySQL.
 T
obuild thisbridge sothat data cantravel both ways we
need a connectorcalled “mysql.connector”.
 We can install “mysql.connector” by using following
methods:
At commandprompt (Administrator login)
 Type“pip install mysql.connector”and press enter
 (internet connectionin required)
 Thisconnector will work only for MySQL5.7.3 orlater
Or open
“https://dev.mysql.com/downloads/connector/python/”
Connectingto MySQLfrom Python
 Oncethe connectorisinstalled youare ready to
connectyour python program to MySQL.
 Thefollowing stepsto follow while connectingyour
python program with MySQL
Open python
Import the package required (import mysql.connector)
Open the connectionto database
Create a cursor instance
Executethe query and store it in resultset
Extract data from resultset
Clean up the environment
Importing mysql.connector
import mysql.connector
Or
import mysql.connectoras ms
Here“ms”isan alias, soevery time wecanuse“ms”in
place of “mysql.connector”
Open a connection toMySQL Database
 T
ocreate connection,connect()function isused
 Itssyntaxis:
connect(host=<server_name>,user=<user_name>,
passwd=<password>[,database=<database>])
 Here server_namemeansdatabase servername, generally
it isgiven as“localhost”
 User_namemeansuserby whichwe connectwith mysql
generally it isgiven as “root”
 Passwdisthe password of user“root”
 Database isthe nameof database whosedata(table) we
want to use
Example: Toestablish connection with MySQL
is_connected() function returns
true if connection isestablished
otherwise false
“mys” isan alias of package “mysql.connector”
Creating Cursor
 It isa usefulcontrol structure of database connectivity.
 When we fire a query to database, it is executed and
resultset (set of records) is sent over theconnectionin one
go.
 We may want to access data one row at a time, but
query processing cannot happens as one row at a time,
socursor help usin performing this task. Cursor stores all
the data as a temporary container of returned data
and wecanfetch data onerow at a time from Cursor.
Creating Cursor and Executing Query
 TO CREATE CURSOR
Cursor_name= connectionObject.cursor()
For e.g.
mycursor= mycon.cursor()
 TO EXECUTE QUERY
 We useexecute()function to sendquery to connection
 Cursor_name.execute(query)
 For e.g.
 mycursor.execute("select* from emp")
Example- Cursor
Output shows cursor is created and query is fired and stored, but no data is
coming. T
o fetch data we have to use functions like fetchall(), fetchone(),
fetchmany() are used
Fetching(extracting) data from ResultSet
 T
oextract data from cursorfollowing functionsare used:
fetchall() :it will return all the record in the form of listof
tuples.
fetchone() : it return one record from the result set. i.e.
first time it will return first record, next time it will return
second record and so on. If no more record it will return
None
fetchmany(n) : it will return n number of records. It no
morerecord it will return an empty list.
rowcount : it will return number of rows retrieved from
the cursorsofar.
Table to work (emp)
Example– fetchall()
Example4: fetchone()
Example5: fetchmany(n)
Parameterized Query
 We can pass values to query to perform dynamic
search like we want to search for any employee
number entered during runtime or to search any
other column values.
 T
o Create Parameterized query we can use various
methods like:
Concatenating dynamic variable to query
valuesare entered.
String template with % formatting
String template with {} and format function
in which
Concatenating variable with query
String template with %sformatting
 Inthismethodwewill use%sin place of valuesto
substituteand thenpassthe value for that place.
String template with %sformatting
String templatewith {} and format()
 Inthis method in place of %swe will use{} and to pass
valuesfor theseplaceholder format() isused. Insidewe
canoptionally give 0,1,2… valuesfor e.g.
{0},{1} but its not mandatory. we can also optionally
passnamedparameter inside {} sothat whilepassing
we need
to pass.
of
value
not to
For e.g.
values through format function
remember the order
{roll},{name} etc.
String templatewith {} and format()
String templatewith {} and format()
Interface Python with MySQL connectivity.pptx
Inserting data in MySQL table from Python
 INSERT, UPDATE AND DELETE operation are
executed in the same way we execute SELECTquery
using execute() but one thing to remember, after
executing insert or update query we must commit
our query using connectionobjectwith commit().
 Fore.g. (if our connectionobject nameis mycon)
 mycon.commit()
Example: inserting data
BEFORE PROGRAM EXECUTION
AFTER PROGRAM EXECUTION
Example: Updating record

More Related Content

PPTX
SQL-Connectivity python for beginners easy explanation with concepts and outp...
PPTX
015. Interface Python with sql interface ppt class 12
PPTX
Interface Python with MySQLwedgvwewefwefwe.pptx
PDF
Interface Python with MySQL.pdf
PPTX
Database Connectivity using Python and MySQL
PPT
Php and MySQL Web Development
PDF
9 Python programming notes for ktu physics and computer application semester 4
SQL-Connectivity python for beginners easy explanation with concepts and outp...
015. Interface Python with sql interface ppt class 12
Interface Python with MySQLwedgvwewefwefwe.pptx
Interface Python with MySQL.pdf
Database Connectivity using Python and MySQL
Php and MySQL Web Development
9 Python programming notes for ktu physics and computer application semester 4

Similar to Interface Python with MySQL connectivity.pptx (20)

PPTX
interface with mysql.pptx
PPT
Lect_04b_PhpMysqlKEY PERFORMANCE INDICATOR FOR ICT-UNIT (new).ppt
PPT
JDBC – Java Database Connectivity
PPT
Python session 10
PPTX
MySql Interface database in sql python my.pptx
PPTX
Node js crash course session 5
PDF
java4th.pdf bilgisayar mühendisliği bölümü
PPTX
Interfacing python to mysql (11363255151).pptx
ODP
ODP
DOCX
Android database tutorial
PDF
24. SQL .pdf
PPTX
Csharp_dotnet_ADO_Net_database_query.pptx
PDF
Java 1-contd
PPTX
Pyhton with Mysql to perform CRUD operations.pptx
PDF
Fnt Software Solutions Pvt Ltd Placement Papers - PHP Technology
DOCX
Php interview questions
PPT
Executing Sql Commands
PPT
Executing Sql Commands
interface with mysql.pptx
Lect_04b_PhpMysqlKEY PERFORMANCE INDICATOR FOR ICT-UNIT (new).ppt
JDBC – Java Database Connectivity
Python session 10
MySql Interface database in sql python my.pptx
Node js crash course session 5
java4th.pdf bilgisayar mühendisliği bölümü
Interfacing python to mysql (11363255151).pptx
Android database tutorial
24. SQL .pdf
Csharp_dotnet_ADO_Net_database_query.pptx
Java 1-contd
Pyhton with Mysql to perform CRUD operations.pptx
Fnt Software Solutions Pvt Ltd Placement Papers - PHP Technology
Php interview questions
Executing Sql Commands
Executing Sql Commands
Ad

Recently uploaded (20)

PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
master seminar digital applications in india
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
Cell Types and Its function , kingdom of life
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Classroom Observation Tools for Teachers
PDF
A systematic review of self-coping strategies used by university students to ...
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
Computing-Curriculum for Schools in Ghana
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
Presentation on HIE in infants and its manifestations
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
O5-L3 Freight Transport Ops (International) V1.pdf
master seminar digital applications in india
102 student loan defaulters named and shamed – Is someone you know on the list?
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Module 4: Burden of Disease Tutorial Slides S2 2025
Supply Chain Operations Speaking Notes -ICLT Program
Cell Types and Its function , kingdom of life
STATICS OF THE RIGID BODIES Hibbelers.pdf
O7-L3 Supply Chain Operations - ICLT Program
Microbial diseases, their pathogenesis and prophylaxis
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Classroom Observation Tools for Teachers
A systematic review of self-coping strategies used by university students to ...
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Computing-Curriculum for Schools in Ghana
GDM (1) (1).pptx small presentation for students
Presentation on HIE in infants and its manifestations
human mycosis Human fungal infections are called human mycosis..pptx
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Ad

Interface Python with MySQL connectivity.pptx

  • 2. Introduction  Every application required data to be stored for future reference to manipulate data. Today every application storesdata in database for this purpose  For example, reservation system stores passengers details for reserving the seats and later on for sending somemessagesor for printing tickets etc.  Python allows us to connect all types of database like Oracle, SQLServer, MySQL.
  • 3. Pre-requisite to connectPythonwith MySQL  Before we connect python program with any database like MySQL we need to build a bridge to connect PythonandMySQL.  T obuild thisbridge sothat data cantravel both ways we need a connectorcalled “mysql.connector”.  We can install “mysql.connector” by using following methods: At commandprompt (Administrator login)  Type“pip install mysql.connector”and press enter  (internet connectionin required)  Thisconnector will work only for MySQL5.7.3 orlater Or open “https://dev.mysql.com/downloads/connector/python/”
  • 4. Connectingto MySQLfrom Python  Oncethe connectorisinstalled youare ready to connectyour python program to MySQL.  Thefollowing stepsto follow while connectingyour python program with MySQL Open python Import the package required (import mysql.connector) Open the connectionto database Create a cursor instance Executethe query and store it in resultset Extract data from resultset Clean up the environment
  • 5. Importing mysql.connector import mysql.connector Or import mysql.connectoras ms Here“ms”isan alias, soevery time wecanuse“ms”in place of “mysql.connector”
  • 6. Open a connection toMySQL Database  T ocreate connection,connect()function isused  Itssyntaxis: connect(host=<server_name>,user=<user_name>, passwd=<password>[,database=<database>])  Here server_namemeansdatabase servername, generally it isgiven as“localhost”  User_namemeansuserby whichwe connectwith mysql generally it isgiven as “root”  Passwdisthe password of user“root”  Database isthe nameof database whosedata(table) we want to use
  • 7. Example: Toestablish connection with MySQL is_connected() function returns true if connection isestablished otherwise false “mys” isan alias of package “mysql.connector”
  • 8. Creating Cursor  It isa usefulcontrol structure of database connectivity.  When we fire a query to database, it is executed and resultset (set of records) is sent over theconnectionin one go.  We may want to access data one row at a time, but query processing cannot happens as one row at a time, socursor help usin performing this task. Cursor stores all the data as a temporary container of returned data and wecanfetch data onerow at a time from Cursor.
  • 9. Creating Cursor and Executing Query  TO CREATE CURSOR Cursor_name= connectionObject.cursor() For e.g. mycursor= mycon.cursor()  TO EXECUTE QUERY  We useexecute()function to sendquery to connection  Cursor_name.execute(query)  For e.g.  mycursor.execute("select* from emp")
  • 10. Example- Cursor Output shows cursor is created and query is fired and stored, but no data is coming. T o fetch data we have to use functions like fetchall(), fetchone(), fetchmany() are used
  • 11. Fetching(extracting) data from ResultSet  T oextract data from cursorfollowing functionsare used: fetchall() :it will return all the record in the form of listof tuples. fetchone() : it return one record from the result set. i.e. first time it will return first record, next time it will return second record and so on. If no more record it will return None fetchmany(n) : it will return n number of records. It no morerecord it will return an empty list. rowcount : it will return number of rows retrieved from the cursorsofar.
  • 12. Table to work (emp)
  • 16. Parameterized Query  We can pass values to query to perform dynamic search like we want to search for any employee number entered during runtime or to search any other column values.  T o Create Parameterized query we can use various methods like: Concatenating dynamic variable to query valuesare entered. String template with % formatting String template with {} and format function in which
  • 18. String template with %sformatting  Inthismethodwewill use%sin place of valuesto substituteand thenpassthe value for that place.
  • 19. String template with %sformatting
  • 20. String templatewith {} and format()  Inthis method in place of %swe will use{} and to pass valuesfor theseplaceholder format() isused. Insidewe canoptionally give 0,1,2… valuesfor e.g. {0},{1} but its not mandatory. we can also optionally passnamedparameter inside {} sothat whilepassing we need to pass. of value not to For e.g. values through format function remember the order {roll},{name} etc.
  • 21. String templatewith {} and format()
  • 22. String templatewith {} and format()
  • 24. Inserting data in MySQL table from Python  INSERT, UPDATE AND DELETE operation are executed in the same way we execute SELECTquery using execute() but one thing to remember, after executing insert or update query we must commit our query using connectionobjectwith commit().  Fore.g. (if our connectionobject nameis mycon)  mycon.commit()
  • 25. Example: inserting data BEFORE PROGRAM EXECUTION AFTER PROGRAM EXECUTION