SlideShare a Scribd company logo
1 of 28
Download to read offline
INTERFACE PYTHON WITH
MYSQL
Connecting Python application with MySQL
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
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), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
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), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
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), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
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), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
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), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
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), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Table to work (emp)
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
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), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
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), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
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), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
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), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Example – fetchall()
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Example 2 – fetchall()
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Example 3 – fetchall()
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Example 4: fetchone()
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Example 5: fetchmany(n)
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Guess the output
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
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), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Concatenating variable with query
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
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), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
String template with %s formatting
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
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), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
String template with {} and format()
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
String template with {} and format()
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
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), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Example : inserting data
BEFORE PROGRAM EXECUTION
AFTER PROGRAM EXECUTION
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Example: Updating record
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com

More Related Content

Similar to 015. Interface Python with MySQL.pdf

PythonWebConference_ Cloud Native Apache Pulsar Development 202 with Python
PythonWebConference_ Cloud Native Apache Pulsar Development 202 with PythonPythonWebConference_ Cloud Native Apache Pulsar Development 202 with Python
PythonWebConference_ Cloud Native Apache Pulsar Development 202 with PythonTimothy Spann
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomyDongmin Yu
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기NAVER D2
 
Ft10 de smet
Ft10 de smetFt10 de smet
Ft10 de smetnkaluva
 
30 5 Database Jdbc
30 5 Database Jdbc30 5 Database Jdbc
30 5 Database Jdbcphanleson
 
Scylla Summit 2016: Analytics Show Time - Spark and Presto Powered by Scylla
Scylla Summit 2016: Analytics Show Time - Spark and Presto Powered by ScyllaScylla Summit 2016: Analytics Show Time - Spark and Presto Powered by Scylla
Scylla Summit 2016: Analytics Show Time - Spark and Presto Powered by ScyllaScyllaDB
 
How Pony ORM translates Python generators to SQL queries
How Pony ORM translates Python generators to SQL queriesHow Pony ORM translates Python generators to SQL queries
How Pony ORM translates Python generators to SQL queriesponyorm
 
014 TUPLES.pdf
014 TUPLES.pdf014 TUPLES.pdf
014 TUPLES.pdfamman23
 
What is the best full text search engine for Python?
What is the best full text search engine for Python?What is the best full text search engine for Python?
What is the best full text search engine for Python?Andrii Soldatenko
 
KSQL - Stream Processing simplified!
KSQL - Stream Processing simplified!KSQL - Stream Processing simplified!
KSQL - Stream Processing simplified!Guido Schmutz
 
Apache Spark Structured Streaming + Apache Kafka = ♡
Apache Spark Structured Streaming + Apache Kafka = ♡Apache Spark Structured Streaming + Apache Kafka = ♡
Apache Spark Structured Streaming + Apache Kafka = ♡Bartosz Konieczny
 
17 PYTHON MODULES-2.pdf
17 PYTHON MODULES-2.pdf17 PYTHON MODULES-2.pdf
17 PYTHON MODULES-2.pdfJeevithaG22
 
Bring Your Own Apache MXNet and TensorFlow Scripts to Amazon SageMaker (AIM35...
Bring Your Own Apache MXNet and TensorFlow Scripts to Amazon SageMaker (AIM35...Bring Your Own Apache MXNet and TensorFlow Scripts to Amazon SageMaker (AIM35...
Bring Your Own Apache MXNet and TensorFlow Scripts to Amazon SageMaker (AIM35...Amazon Web Services
 
Creating the PromQL Transpiler for Flux by Julius Volz, Co-Founder | Prometheus
Creating the PromQL Transpiler for Flux by Julius Volz, Co-Founder | PrometheusCreating the PromQL Transpiler for Flux by Julius Volz, Co-Founder | Prometheus
Creating the PromQL Transpiler for Flux by Julius Volz, Co-Founder | PrometheusInfluxData
 
The Atmosphere Framework
The Atmosphere FrameworkThe Atmosphere Framework
The Atmosphere Frameworkjfarcand
 
Build a Complex, Realtime Data Management App with Postgres 14!
Build a Complex, Realtime Data Management App with Postgres 14!Build a Complex, Realtime Data Management App with Postgres 14!
Build a Complex, Realtime Data Management App with Postgres 14!Jonathan Katz
 
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)James Titcumb
 
Add (Syntactic) Sugar To Your Java
Add (Syntactic) Sugar To Your JavaAdd (Syntactic) Sugar To Your Java
Add (Syntactic) Sugar To Your JavaPascal-Louis Perez
 
Embedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for JavaEmbedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for JavaJevgeni Kabanov
 
Writing RESTful web services using Node.js
Writing RESTful web services using Node.jsWriting RESTful web services using Node.js
Writing RESTful web services using Node.jsFDConf
 

Similar to 015. Interface Python with MySQL.pdf (20)

PythonWebConference_ Cloud Native Apache Pulsar Development 202 with Python
PythonWebConference_ Cloud Native Apache Pulsar Development 202 with PythonPythonWebConference_ Cloud Native Apache Pulsar Development 202 with Python
PythonWebConference_ Cloud Native Apache Pulsar Development 202 with Python
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomy
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기
 
Ft10 de smet
Ft10 de smetFt10 de smet
Ft10 de smet
 
30 5 Database Jdbc
30 5 Database Jdbc30 5 Database Jdbc
30 5 Database Jdbc
 
Scylla Summit 2016: Analytics Show Time - Spark and Presto Powered by Scylla
Scylla Summit 2016: Analytics Show Time - Spark and Presto Powered by ScyllaScylla Summit 2016: Analytics Show Time - Spark and Presto Powered by Scylla
Scylla Summit 2016: Analytics Show Time - Spark and Presto Powered by Scylla
 
How Pony ORM translates Python generators to SQL queries
How Pony ORM translates Python generators to SQL queriesHow Pony ORM translates Python generators to SQL queries
How Pony ORM translates Python generators to SQL queries
 
014 TUPLES.pdf
014 TUPLES.pdf014 TUPLES.pdf
014 TUPLES.pdf
 
What is the best full text search engine for Python?
What is the best full text search engine for Python?What is the best full text search engine for Python?
What is the best full text search engine for Python?
 
KSQL - Stream Processing simplified!
KSQL - Stream Processing simplified!KSQL - Stream Processing simplified!
KSQL - Stream Processing simplified!
 
Apache Spark Structured Streaming + Apache Kafka = ♡
Apache Spark Structured Streaming + Apache Kafka = ♡Apache Spark Structured Streaming + Apache Kafka = ♡
Apache Spark Structured Streaming + Apache Kafka = ♡
 
17 PYTHON MODULES-2.pdf
17 PYTHON MODULES-2.pdf17 PYTHON MODULES-2.pdf
17 PYTHON MODULES-2.pdf
 
Bring Your Own Apache MXNet and TensorFlow Scripts to Amazon SageMaker (AIM35...
Bring Your Own Apache MXNet and TensorFlow Scripts to Amazon SageMaker (AIM35...Bring Your Own Apache MXNet and TensorFlow Scripts to Amazon SageMaker (AIM35...
Bring Your Own Apache MXNet and TensorFlow Scripts to Amazon SageMaker (AIM35...
 
Creating the PromQL Transpiler for Flux by Julius Volz, Co-Founder | Prometheus
Creating the PromQL Transpiler for Flux by Julius Volz, Co-Founder | PrometheusCreating the PromQL Transpiler for Flux by Julius Volz, Co-Founder | Prometheus
Creating the PromQL Transpiler for Flux by Julius Volz, Co-Founder | Prometheus
 
The Atmosphere Framework
The Atmosphere FrameworkThe Atmosphere Framework
The Atmosphere Framework
 
Build a Complex, Realtime Data Management App with Postgres 14!
Build a Complex, Realtime Data Management App with Postgres 14!Build a Complex, Realtime Data Management App with Postgres 14!
Build a Complex, Realtime Data Management App with Postgres 14!
 
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)
 
Add (Syntactic) Sugar To Your Java
Add (Syntactic) Sugar To Your JavaAdd (Syntactic) Sugar To Your Java
Add (Syntactic) Sugar To Your Java
 
Embedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for JavaEmbedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for Java
 
Writing RESTful web services using Node.js
Writing RESTful web services using Node.jsWriting RESTful web services using Node.js
Writing RESTful web services using Node.js
 

Recently uploaded

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 

Recently uploaded (20)

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 

015. Interface Python with MySQL.pdf

  • 1. INTERFACE PYTHON WITH MYSQL Connecting Python application with MySQL VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 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), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 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), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 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), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 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), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 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), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 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), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 8. Table to work (emp) VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 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), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 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), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 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), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 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), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 13. Example – fetchall() VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 14. Example 2 – fetchall() VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 15. Example 3 – fetchall() VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 16. Example 4: fetchone() VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 17. Example 5: fetchmany(n) VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 18. Guess the output VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 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), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 20. Concatenating variable with query VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 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), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 22. String template with %s formatting VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 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), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 24. String template with {} and format() VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 25. String template with {} and format() VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 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), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 27. Example : inserting data BEFORE PROGRAM EXECUTION AFTER PROGRAM EXECUTION VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com
  • 28. Example: Updating record VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR for more updates visit: www.python4csip.com