SlideShare a Scribd company logo
INTERFACE PYTHON WITH
MYSQL
Connecting Python application with MySQL
Introduction
 Every application required data to be stored for future
reference to manipulate data. Today every application
stores data in database for this purpose
 For example, reservation system stores passengers
details for reserving the seats and later on for sending
some messages or for printing tickets etc.
 In school student details are saved for many reasons
like attendance, fee collections, exams, report card etc.
 Python allows us to connect all types of database like
Oracle, SQL Server, MySQL.
 In our syllabus we have to understand how to connect
Python programs with MySQL
VINOD KUMAR VERMA, PGT(CS)
Pre-requisite to connect Python with
MySQL
 Before we connect python program with any database
like MySQL we need to build a bridge to connect
Python and MySQL.
 To build this bridge so that data can travel both ways
we need a connector called “mysql.connector”.
 We can install “mysql.connector” by using following
methods:
 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
“https://dev.mysql.com/downloads/connector/python/”
and download connector as per OS and Python version
VINOD KUMAR VERMA, PGT(CS)
Connecting to MySQL from Python
 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
 Clean up the environment
VINOD KUMAR VERMA, PGT(CS)
Importing mysql.connector
import mysql.connector
Or
import mysql.connector as ms
Here “ms” is an alias, so every time we can use “ms” in
place of “mysql.connector”
VINOD KUMAR VERMA, PGT(CS)
Open a connection to MySQL Database
 To create connection, connect() function is used
 Its syntax is:
 connect(host=<server_name>,user=<user_name>,
passwd=<password>[,database=<database>])
 Here server_name means database servername, generally
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
VINOD KUMAR VERMA, PGT(CS)
Example: To establish connection with MySQL
is_connected() function returns
true if connection is established
otherwise false
“mys” is an alias of package “mysql.connector”
“mycon” is connection object which stores connection established with MySQL
“connect()” function is used to connect with mysql by specifying parameters
like host, user, passwd, database
VINOD KUMAR VERMA, PGT(CS)
Table to work (emp)
VINOD KUMAR VERMA, PGT(CS)
Creating Cursor
 It is a useful control structure of database connectivity.
 When we fire a query to database, it is executed and
resultset (set of records) is sent over he connection in
one go.
 We may want to access data one row at a time, but
query processing cannot happens as one row at a time,
so cursor help us in performing this task. Cursor stores
all the data as a temporary container of returned data
and we can fetch data one row at a time from Cursor.
VINOD KUMAR VERMA, PGT(CS)
Creating Cursor and Executing Query
 TO CREATE CURSOR
 Cursor_name = connectionObject.cursor()
 For e.g.
 mycursor = mycon.cursor()
 TO EXECUTE QUERY
 We use execute() function to send query to connection
 Cursor_name.execute(query)
 For e.g.
 mycursor.execute(‘select * from emp’)
VINOD KUMAR VERMA, PGT(CS)
Example - Cursor
Output shows cursor is created and query is fired and stored, but no data is
coming. To fetch data we have to use functions like fetchall(), fetchone(),
fetchmany() are used
VINOD KUMAR VERMA, PGT(CS)
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.
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
more record it will return an empty tuple.
 rowcount : it will return number of rows retrieved from
the cursor so far.
VINOD KUMAR VERMA, PGT(CS)
Example – fetchall()
VINOD KUMAR VERMA, PGT(CS)
Example 2 – fetchall()
VINOD KUMAR VERMA, PGT(CS)
Example 3 – fetchall()
VINOD KUMAR VERMA, PGT(CS)
Example 4: fetchone()
VINOD KUMAR VERMA, PGT(CS)
Example 5: fetchmany(n)
VINOD KUMAR VERMA, PGT(CS)
Guess the output
VINOD KUMAR VERMA, PGT(CS)
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.
 To Create Parameterized query we can use various
methods like:
 Concatenating dynamic variable to query in which
values are entered.
 String template with % formatting
 String template with {} and format function
VINOD KUMAR VERMA, PGT(CS)
Concatenating variable with query
VINOD KUMAR VERMA, PGT(CS)
String template with %s formatting
 In this method we will use %s in place of values to
substitute and then pass the value for that place.
VINOD KUMAR VERMA, PGT(CS)
String template with %s formatting
VINOD KUMAR VERMA, PGT(CS)
String template with {} and format()
 In this method in place of %s we will use {} and to
pass values for these placeholder format() is used.
Inside we can optionally give 0,1,2… values for e.g.
{0},{1} but its not mandatory. we can also optionally
pass named parameter inside {} so that while passing
values through format function we need not to
remember the order of value to pass. For e.g.
{roll},{name} etc.
VINOD KUMAR VERMA, PGT(CS)
String template with {} and format()
VINOD KUMAR VERMA, PGT(CS)
String template with {} and format()
VINOD KUMAR VERMA, PGT(CS)
Inserting data in MySQL table from Python
 INSERT and UPDATE operation are executed in the
same way we execute SELECT query using execute()
but one thing to remember, after executing insert or
update query we must commit our query using
connection object with commit().
 For e.g. (if our connection object name is mycon)
 mycon.commit()
VINOD KUMAR VERMA, PGT(CS)
Example : inserting data
BEFORE PROGRAM EXECUTION
AFTER PROGRAM EXECUTION
VINOD KUMAR VERMA, PGT(CS)
Example: Updating record
VINOD KUMAR VERMA, PGT(CS)

More Related Content

What's hot (20)

Get Connected
Get ConnectedGet Connected
Get Connected
Abdul Wahab
 
Method overriding
Method overridingMethod overriding
Method overriding
Azaz Maverick
 
sed(1)
sed(1)sed(1)
sed(1)
Bipul Kumar
 
Sorting arrays in PHP
Sorting arrays in PHPSorting arrays in PHP
Sorting arrays in PHP
Vineet Kumar Saini
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programming
Damian T. Gordon
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
Alex Miller
 
A Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIOA Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIO
Jorge Vásquez
 
Lagopus + DockerのDPDK接続
Lagopus + DockerのDPDK接続Lagopus + DockerのDPDK接続
Lagopus + DockerのDPDK接続
Tomoya Hibi
 
interface with mysql.pptx
interface with mysql.pptxinterface with mysql.pptx
interface with mysql.pptx
KRITIKAOJHA11
 
Java script -23jan2015
Java script -23jan2015Java script -23jan2015
Java script -23jan2015
Sasidhar Kothuru
 
MongoDB: How it Works
MongoDB: How it WorksMongoDB: How it Works
MongoDB: How it Works
Mike Dirolf
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
Anton Keks
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
amiable_indian
 
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
vikram mahendra
 
Socket programming
Socket programming Socket programming
Socket programming
Rajivarnan (Rajiv)
 
Python Deserialization Attacks
Python Deserialization AttacksPython Deserialization Attacks
Python Deserialization Attacks
NSConclave
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco
 
Java - Sockets
Java - SocketsJava - Sockets
Java - Sockets
Riccardo Cardin
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
_هي الديمقراطية؟.pptx
_هي الديمقراطية؟.pptx_هي الديمقراطية؟.pptx
_هي الديمقراطية؟.pptx
AbdulhussienAljebory1
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programming
Damian T. Gordon
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
Alex Miller
 
A Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIOA Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIO
Jorge Vásquez
 
Lagopus + DockerのDPDK接続
Lagopus + DockerのDPDK接続Lagopus + DockerのDPDK接続
Lagopus + DockerのDPDK接続
Tomoya Hibi
 
interface with mysql.pptx
interface with mysql.pptxinterface with mysql.pptx
interface with mysql.pptx
KRITIKAOJHA11
 
MongoDB: How it Works
MongoDB: How it WorksMongoDB: How it Works
MongoDB: How it Works
Mike Dirolf
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
Anton Keks
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
amiable_indian
 
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
vikram mahendra
 
Python Deserialization Attacks
Python Deserialization AttacksPython Deserialization Attacks
Python Deserialization Attacks
NSConclave
 

Similar to Interface Python with MySQL.pdf (20)

015. Interface Python with sql interface ppt class 12
015. Interface Python with sql interface ppt class 12015. Interface Python with sql interface ppt class 12
015. Interface Python with sql interface ppt class 12
Shuvanth
 
SQL-Connectivity python for beginners easy explanation with concepts and outp...
SQL-Connectivity python for beginners easy explanation with concepts and outp...SQL-Connectivity python for beginners easy explanation with concepts and outp...
SQL-Connectivity python for beginners easy explanation with concepts and outp...
harshitagrawal2608
 
Interface Python with MySQLwedgvwewefwefwe.pptx
Interface Python with MySQLwedgvwewefwefwe.pptxInterface Python with MySQLwedgvwewefwefwe.pptx
Interface Python with MySQLwedgvwewefwefwe.pptx
AyushKumarXIthclass
 
Interface Python with MySQL connectivity.pptx
Interface Python with MySQL connectivity.pptxInterface Python with MySQL connectivity.pptx
Interface Python with MySQL connectivity.pptx
BEENAHASSINA1
 
015. Interface Python with MySQL.pdf
015. Interface Python with MySQL.pdf015. Interface Python with MySQL.pdf
015. Interface Python with MySQL.pdf
SuneetaSingh28
 
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptxPYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
HistoryScienceWorld
 
python db connection samples and program
python db connection samples and programpython db connection samples and program
python db connection samples and program
usha raj
 
Python with MySql.pptx
Python with MySql.pptxPython with MySql.pptx
Python with MySql.pptx
Ramakrishna Reddy Bijjam
 
MySql Interface database in sql python my.pptx
MySql Interface database in sql python my.pptxMySql Interface database in sql python my.pptx
MySql Interface database in sql python my.pptx
UshimArora
 
24. SQL .pdf
24. SQL .pdf24. SQL .pdf
24. SQL .pdf
Bhavya103897
 
Interfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptxInterfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptx
cavicav231
 
PythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for DatabasePythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for Database
dharawagh9999
 
Python database access
Python database accessPython database access
Python database access
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
baabtra.com - No. 1 supplier of quality freshers
 
unit-5 SQL 1 creating a databse connection.pptx
unit-5 SQL 1 creating a databse connection.pptxunit-5 SQL 1 creating a databse connection.pptx
unit-5 SQL 1 creating a databse connection.pptx
HuzaifaAhmedFarooqi
 
Database Connectivity using Python and MySQL
Database Connectivity using Python and MySQLDatabase Connectivity using Python and MySQL
Database Connectivity using Python and MySQL
devsuchaye
 
Database programming
Database programmingDatabase programming
Database programming
Shree M.L.Kakadiya MCA mahila college, Amreli
 
Interface python with sql database10.pdf
Interface python with sql database10.pdfInterface python with sql database10.pdf
Interface python with sql database10.pdf
HiteshNandi
 
Interface python with sql database.pdf--
Interface python with sql database.pdf--Interface python with sql database.pdf--
Interface python with sql database.pdf--
jagaspeed09
 
Interface python with sql database.pdf
Interface python with sql database.pdfInterface python with sql database.pdf
Interface python with sql database.pdf
MohammadImran709594
 
015. Interface Python with sql interface ppt class 12
015. Interface Python with sql interface ppt class 12015. Interface Python with sql interface ppt class 12
015. Interface Python with sql interface ppt class 12
Shuvanth
 
SQL-Connectivity python for beginners easy explanation with concepts and outp...
SQL-Connectivity python for beginners easy explanation with concepts and outp...SQL-Connectivity python for beginners easy explanation with concepts and outp...
SQL-Connectivity python for beginners easy explanation with concepts and outp...
harshitagrawal2608
 
Interface Python with MySQLwedgvwewefwefwe.pptx
Interface Python with MySQLwedgvwewefwefwe.pptxInterface Python with MySQLwedgvwewefwefwe.pptx
Interface Python with MySQLwedgvwewefwefwe.pptx
AyushKumarXIthclass
 
Interface Python with MySQL connectivity.pptx
Interface Python with MySQL connectivity.pptxInterface Python with MySQL connectivity.pptx
Interface Python with MySQL connectivity.pptx
BEENAHASSINA1
 
015. Interface Python with MySQL.pdf
015. Interface Python with MySQL.pdf015. Interface Python with MySQL.pdf
015. Interface Python with MySQL.pdf
SuneetaSingh28
 
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptxPYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
HistoryScienceWorld
 
python db connection samples and program
python db connection samples and programpython db connection samples and program
python db connection samples and program
usha raj
 
MySql Interface database in sql python my.pptx
MySql Interface database in sql python my.pptxMySql Interface database in sql python my.pptx
MySql Interface database in sql python my.pptx
UshimArora
 
Interfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptxInterfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptx
cavicav231
 
PythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for DatabasePythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for Database
dharawagh9999
 
unit-5 SQL 1 creating a databse connection.pptx
unit-5 SQL 1 creating a databse connection.pptxunit-5 SQL 1 creating a databse connection.pptx
unit-5 SQL 1 creating a databse connection.pptx
HuzaifaAhmedFarooqi
 
Database Connectivity using Python and MySQL
Database Connectivity using Python and MySQLDatabase Connectivity using Python and MySQL
Database Connectivity using Python and MySQL
devsuchaye
 
Interface python with sql database10.pdf
Interface python with sql database10.pdfInterface python with sql database10.pdf
Interface python with sql database10.pdf
HiteshNandi
 
Interface python with sql database.pdf--
Interface python with sql database.pdf--Interface python with sql database.pdf--
Interface python with sql database.pdf--
jagaspeed09
 
Interface python with sql database.pdf
Interface python with sql database.pdfInterface python with sql database.pdf
Interface python with sql database.pdf
MohammadImran709594
 
Ad

Recently uploaded (20)

"Dictyoptera: The Order of Cockroaches and Mantises" Or, more specifically: ...
"Dictyoptera: The Order of Cockroaches and Mantises"  Or, more specifically: ..."Dictyoptera: The Order of Cockroaches and Mantises"  Or, more specifically: ...
"Dictyoptera: The Order of Cockroaches and Mantises" Or, more specifically: ...
Arshad Shaikh
 
How to Configure Add to Cart in Odoo 18 Website
How to Configure Add to Cart in Odoo 18 WebsiteHow to Configure Add to Cart in Odoo 18 Website
How to Configure Add to Cart in Odoo 18 Website
Celine George
 
Exploring Identity Through Colombian Companies
Exploring Identity Through Colombian CompaniesExploring Identity Through Colombian Companies
Exploring Identity Through Colombian Companies
OlgaLeonorTorresSnch
 
Multicultural approach in education - B.Ed
Multicultural approach in education - B.EdMulticultural approach in education - B.Ed
Multicultural approach in education - B.Ed
prathimagowda443
 
Cloud Computing ..PPT ( Faizan ALTAF )..
Cloud Computing ..PPT ( Faizan ALTAF )..Cloud Computing ..PPT ( Faizan ALTAF )..
Cloud Computing ..PPT ( Faizan ALTAF )..
faizanaltaf231
 
"Orthoptera: Grasshoppers, Crickets, and Katydids pptx
"Orthoptera: Grasshoppers, Crickets, and Katydids pptx"Orthoptera: Grasshoppers, Crickets, and Katydids pptx
"Orthoptera: Grasshoppers, Crickets, and Katydids pptx
Arshad Shaikh
 
State institute of educational technology
State institute of educational technologyState institute of educational technology
State institute of educational technology
vp5806484
 
QUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptx
QUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptxQUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptx
QUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptx
Sourav Kr Podder
 
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...
wygalkelceqg
 
LDMMIA About me 2025 Edition 3 College Volume
LDMMIA About me 2025 Edition 3 College VolumeLDMMIA About me 2025 Edition 3 College Volume
LDMMIA About me 2025 Edition 3 College Volume
LDM & Mia eStudios
 
Coleoptera: The Largest Insect Order.pptx
Coleoptera: The Largest Insect Order.pptxColeoptera: The Largest Insect Order.pptx
Coleoptera: The Largest Insect Order.pptx
Arshad Shaikh
 
How to Setup Renewal of Subscription in Odoo 18
How to Setup Renewal of Subscription in Odoo 18How to Setup Renewal of Subscription in Odoo 18
How to Setup Renewal of Subscription in Odoo 18
Celine George
 
প্রত্যুৎপন্নমতিত্ব - Prottutponnomotittwa 2025.pdf
প্রত্যুৎপন্নমতিত্ব - Prottutponnomotittwa 2025.pdfপ্রত্যুৎপন্নমতিত্ব - Prottutponnomotittwa 2025.pdf
প্রত্যুৎপন্নমতিত্ব - Prottutponnomotittwa 2025.pdf
Pragya - UEM Kolkata Quiz Club
 
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdfForestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
ChalaKelbessa
 
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...
RVSPSOA
 
LET´S PRACTICE GRAMMAR USING SIMPLE PAST TENSE
LET´S PRACTICE GRAMMAR USING SIMPLE PAST TENSELET´S PRACTICE GRAMMAR USING SIMPLE PAST TENSE
LET´S PRACTICE GRAMMAR USING SIMPLE PAST TENSE
OlgaLeonorTorresSnch
 
LDMMIA Free Reiki Yoga S7 Weekly Workshops
LDMMIA Free Reiki Yoga S7 Weekly WorkshopsLDMMIA Free Reiki Yoga S7 Weekly Workshops
LDMMIA Free Reiki Yoga S7 Weekly Workshops
LDM & Mia eStudios
 
HUMAN SKELETAL SYSTEM ANATAMY AND PHYSIOLOGY
HUMAN SKELETAL SYSTEM ANATAMY AND PHYSIOLOGYHUMAN SKELETAL SYSTEM ANATAMY AND PHYSIOLOGY
HUMAN SKELETAL SYSTEM ANATAMY AND PHYSIOLOGY
DHARMENDRA SAHU
 
"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx
Arshad Shaikh
 
How to Setup Lunch in Odoo 18 - Odoo guides
How to Setup Lunch in Odoo 18 - Odoo guidesHow to Setup Lunch in Odoo 18 - Odoo guides
How to Setup Lunch in Odoo 18 - Odoo guides
Celine George
 
"Dictyoptera: The Order of Cockroaches and Mantises" Or, more specifically: ...
"Dictyoptera: The Order of Cockroaches and Mantises"  Or, more specifically: ..."Dictyoptera: The Order of Cockroaches and Mantises"  Or, more specifically: ...
"Dictyoptera: The Order of Cockroaches and Mantises" Or, more specifically: ...
Arshad Shaikh
 
How to Configure Add to Cart in Odoo 18 Website
How to Configure Add to Cart in Odoo 18 WebsiteHow to Configure Add to Cart in Odoo 18 Website
How to Configure Add to Cart in Odoo 18 Website
Celine George
 
Exploring Identity Through Colombian Companies
Exploring Identity Through Colombian CompaniesExploring Identity Through Colombian Companies
Exploring Identity Through Colombian Companies
OlgaLeonorTorresSnch
 
Multicultural approach in education - B.Ed
Multicultural approach in education - B.EdMulticultural approach in education - B.Ed
Multicultural approach in education - B.Ed
prathimagowda443
 
Cloud Computing ..PPT ( Faizan ALTAF )..
Cloud Computing ..PPT ( Faizan ALTAF )..Cloud Computing ..PPT ( Faizan ALTAF )..
Cloud Computing ..PPT ( Faizan ALTAF )..
faizanaltaf231
 
"Orthoptera: Grasshoppers, Crickets, and Katydids pptx
"Orthoptera: Grasshoppers, Crickets, and Katydids pptx"Orthoptera: Grasshoppers, Crickets, and Katydids pptx
"Orthoptera: Grasshoppers, Crickets, and Katydids pptx
Arshad Shaikh
 
State institute of educational technology
State institute of educational technologyState institute of educational technology
State institute of educational technology
vp5806484
 
QUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptx
QUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptxQUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptx
QUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptx
Sourav Kr Podder
 
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...
wygalkelceqg
 
LDMMIA About me 2025 Edition 3 College Volume
LDMMIA About me 2025 Edition 3 College VolumeLDMMIA About me 2025 Edition 3 College Volume
LDMMIA About me 2025 Edition 3 College Volume
LDM & Mia eStudios
 
Coleoptera: The Largest Insect Order.pptx
Coleoptera: The Largest Insect Order.pptxColeoptera: The Largest Insect Order.pptx
Coleoptera: The Largest Insect Order.pptx
Arshad Shaikh
 
How to Setup Renewal of Subscription in Odoo 18
How to Setup Renewal of Subscription in Odoo 18How to Setup Renewal of Subscription in Odoo 18
How to Setup Renewal of Subscription in Odoo 18
Celine George
 
প্রত্যুৎপন্নমতিত্ব - Prottutponnomotittwa 2025.pdf
প্রত্যুৎপন্নমতিত্ব - Prottutponnomotittwa 2025.pdfপ্রত্যুৎপন্নমতিত্ব - Prottutponnomotittwa 2025.pdf
প্রত্যুৎপন্নমতিত্ব - Prottutponnomotittwa 2025.pdf
Pragya - UEM Kolkata Quiz Club
 
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdfForestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
ChalaKelbessa
 
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...
RVSPSOA
 
LET´S PRACTICE GRAMMAR USING SIMPLE PAST TENSE
LET´S PRACTICE GRAMMAR USING SIMPLE PAST TENSELET´S PRACTICE GRAMMAR USING SIMPLE PAST TENSE
LET´S PRACTICE GRAMMAR USING SIMPLE PAST TENSE
OlgaLeonorTorresSnch
 
LDMMIA Free Reiki Yoga S7 Weekly Workshops
LDMMIA Free Reiki Yoga S7 Weekly WorkshopsLDMMIA Free Reiki Yoga S7 Weekly Workshops
LDMMIA Free Reiki Yoga S7 Weekly Workshops
LDM & Mia eStudios
 
HUMAN SKELETAL SYSTEM ANATAMY AND PHYSIOLOGY
HUMAN SKELETAL SYSTEM ANATAMY AND PHYSIOLOGYHUMAN SKELETAL SYSTEM ANATAMY AND PHYSIOLOGY
HUMAN SKELETAL SYSTEM ANATAMY AND PHYSIOLOGY
DHARMENDRA SAHU
 
"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx
Arshad Shaikh
 
How to Setup Lunch in Odoo 18 - Odoo guides
How to Setup Lunch in Odoo 18 - Odoo guidesHow to Setup Lunch in Odoo 18 - Odoo guides
How to Setup Lunch in Odoo 18 - Odoo guides
Celine George
 
Ad

Interface Python with MySQL.pdf

  • 1. INTERFACE PYTHON WITH MYSQL Connecting Python application with MySQL
  • 2. Introduction  Every application required data to be stored for future reference to manipulate data. Today every application stores data in database for this purpose  For example, reservation system stores passengers details for reserving the seats and later on for sending some messages or for printing tickets etc.  In school student details are saved for many reasons like attendance, fee collections, exams, report card etc.  Python allows us to connect all types of database like Oracle, SQL Server, MySQL.  In our syllabus we have to understand how to connect Python programs with MySQL VINOD KUMAR VERMA, PGT(CS)
  • 3. Pre-requisite to connect Python with MySQL  Before we connect python program with any database like MySQL we need to build a bridge to connect Python and MySQL.  To build this bridge so that data can travel both ways we need a connector called “mysql.connector”.  We can install “mysql.connector” by using following methods:  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 “https://dev.mysql.com/downloads/connector/python/” and download connector as per OS and Python version VINOD KUMAR VERMA, PGT(CS)
  • 4. Connecting to MySQL from Python  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  Clean up the environment VINOD KUMAR VERMA, PGT(CS)
  • 5. Importing mysql.connector import mysql.connector Or import mysql.connector as ms Here “ms” is an alias, so every time we can use “ms” in place of “mysql.connector” VINOD KUMAR VERMA, PGT(CS)
  • 6. Open a connection to MySQL Database  To create connection, connect() function is used  Its syntax is:  connect(host=<server_name>,user=<user_name>, passwd=<password>[,database=<database>])  Here server_name means database servername, generally 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 VINOD KUMAR VERMA, PGT(CS)
  • 7. Example: To establish connection with MySQL is_connected() function returns true if connection is established otherwise false “mys” is an alias of package “mysql.connector” “mycon” is connection object which stores connection established with MySQL “connect()” function is used to connect with mysql by specifying parameters like host, user, passwd, database VINOD KUMAR VERMA, PGT(CS)
  • 8. Table to work (emp) VINOD KUMAR VERMA, PGT(CS)
  • 9. Creating Cursor  It is a useful control structure of database connectivity.  When we fire a query to database, it is executed and resultset (set of records) is sent over he connection in one go.  We may want to access data one row at a time, but query processing cannot happens as one row at a time, so cursor help us in performing this task. Cursor stores all the data as a temporary container of returned data and we can fetch data one row at a time from Cursor. VINOD KUMAR VERMA, PGT(CS)
  • 10. Creating Cursor and Executing Query  TO CREATE CURSOR  Cursor_name = connectionObject.cursor()  For e.g.  mycursor = mycon.cursor()  TO EXECUTE QUERY  We use execute() function to send query to connection  Cursor_name.execute(query)  For e.g.  mycursor.execute(‘select * from emp’) VINOD KUMAR VERMA, PGT(CS)
  • 11. Example - Cursor Output shows cursor is created and query is fired and stored, but no data is coming. To fetch data we have to use functions like fetchall(), fetchone(), fetchmany() are used VINOD KUMAR VERMA, PGT(CS)
  • 12. 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. 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 more record it will return an empty tuple.  rowcount : it will return number of rows retrieved from the cursor so far. VINOD KUMAR VERMA, PGT(CS)
  • 13. Example – fetchall() VINOD KUMAR VERMA, PGT(CS)
  • 14. Example 2 – fetchall() VINOD KUMAR VERMA, PGT(CS)
  • 15. Example 3 – fetchall() VINOD KUMAR VERMA, PGT(CS)
  • 16. Example 4: fetchone() VINOD KUMAR VERMA, PGT(CS)
  • 17. Example 5: fetchmany(n) VINOD KUMAR VERMA, PGT(CS)
  • 18. Guess the output VINOD KUMAR VERMA, PGT(CS)
  • 19. 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.  To Create Parameterized query we can use various methods like:  Concatenating dynamic variable to query in which values are entered.  String template with % formatting  String template with {} and format function VINOD KUMAR VERMA, PGT(CS)
  • 20. Concatenating variable with query VINOD KUMAR VERMA, PGT(CS)
  • 21. String template with %s formatting  In this method we will use %s in place of values to substitute and then pass the value for that place. VINOD KUMAR VERMA, PGT(CS)
  • 22. String template with %s formatting VINOD KUMAR VERMA, PGT(CS)
  • 23. String template with {} and format()  In this method in place of %s we will use {} and to pass values for these placeholder format() is used. Inside we can optionally give 0,1,2… values for e.g. {0},{1} but its not mandatory. we can also optionally pass named parameter inside {} so that while passing values through format function we need not to remember the order of value to pass. For e.g. {roll},{name} etc. VINOD KUMAR VERMA, PGT(CS)
  • 24. String template with {} and format() VINOD KUMAR VERMA, PGT(CS)
  • 25. String template with {} and format() VINOD KUMAR VERMA, PGT(CS)
  • 26. Inserting data in MySQL table from Python  INSERT and UPDATE operation are executed in the same way we execute SELECT query using execute() but one thing to remember, after executing insert or update query we must commit our query using connection object with commit().  For e.g. (if our connection object name is mycon)  mycon.commit() VINOD KUMAR VERMA, PGT(CS)
  • 27. Example : inserting data BEFORE PROGRAM EXECUTION AFTER PROGRAM EXECUTION VINOD KUMAR VERMA, PGT(CS)
  • 28. Example: Updating record VINOD KUMAR VERMA, PGT(CS)