SlideShare a Scribd company logo
1 of 80
CHAPTER - XVI
INTERFACE PYTHON WITH MYSQL
REFERENCE:
CLASS XII
TEXT BOOK
SUMITA ARORA
INTRODUCTION
INTRODUCTION
Every organisation depends on
large databases. These are essentially
collections of tables, and’ connected with
each other through columns. These database
systems support SQL, the Structured Query
Language, which is used to create, access and
manipulate the data.
INTRODUCTION
The Python programming language has
powerful features for database programming.
Python supports various databases like
MySQL, Oracle, Sybase, PostgreSQL, etc.
Python also supports Data Definition
Language (DDL), Data Manipulation Language
(DML) and Data Query Statements.
INTRODUCTION
For database programming, the Python DB
API is a widely used module that provides a
database application programming interface.
INTERFACE
INTERFACE
What is an Interface?
Interface is the way for an application to
interact with certain system/application.
For
Example:
INTERFACE
API - APPLICATION PROGRAMMING INTERFACE
API -APPLICATION PROGRAMMING INTERFACE
In computer programming, an
application programming interface is a set of
subroutine definitions, communication
protocols, and tools for building software. In
general terms, it is a set of clearly defined
methods of communication among various
components.
Consider an API as a waiter in a
restaurant. Suppose you have a menu of your
favourite food and the kitchen is the system
where your order is made. But how do you
take your order till the kitchen? Correct, you
call a waiter, give him/her the order, which in
turns takes your order till the kitchen and
then your order is made there and then
finally, the waiter comes back with your
delicious ordered food.
API -APPLICATION PROGRAMMING INTERFACE
Thus, the API is very much similar to the
waiter. API is the messenger that takes your
order(waiter) and tells the system(kitchen)
what to do (to prepare food) and in return
gives back the response you asked for (waiter
returns with the ordered food).
API -APPLICATION PROGRAMMING INTERFACE
BENEFITS OF PYTHON FOR DATABASE
PROGRAMMING
There are many good reasons to use Python for
programming database applications:
Programming in Python is arguably more
efficient and faster compared to other
languages.
Python is famous for its portability.
It is platform independent.
BENEFITS OF PYTHON FOR DATABASE
PROGRAMMING
Python supports SQL cursors.
In many programming languages, the
application developer needs to take care of the
open and closed connections of the database, to
avoid further exceptions and errors. In Python,
these connections are taken care of.
BENEFITS OF PYTHON FOR DATABASE
PROGRAMMING
Python supports relational database systems.
Python database APIs are compatible with
various databases, so it is very easy to migrate
and port database application interfaces.
BENEFITS OF PYTHON FOR DATABASE
PROGRAMMING
PYTHON INTEGRATION WITH MYSQL
PYTHON INTEGRATION WITH MYSQL
We discuss how to develop and integrate
Python applications that work with a MySQL
database server. Python is dynamic, and
enterprise language and it has all the support
to build large and complex enterprise
applications. MySQL is the world’s most
powerful and used open-source database
provided by Oracle.
INTRODUCTION
PYTHON INTEGRATION WITH MYSQL
PYTHON MODULE FOR COMMUNICATING WITH MYSQL
PYTHON INTEGRATION WITH MYSQL
Total 5 modules available in python to
communicate with a MySQL and provides
MySQL database support to our applications
and they are:-
1. MySQL Connector Python
2. PyMySQL
3. MySQLDB
4. mysqlclient
5. OurSQL
PYTHON INTEGRATION WITH MYSQL
Note: Above all interfaces or modules are
adhere to Python Database API Specification
v2.0 (PEP 249) that means the syntax, method
and the way of access database is the same in
all.
PEP 249 has been designed to encourage
and maintain similarity between the Python
modules that are used to access databases. By
doing this, above all modules are following
rules defined in Python Database API
Specification v2.0 (PEP 249).
PYTHON INTEGRATION WITH MYSQL
You can choose any of the above modules
as per your requirement. The way of accessing
the MySQL database remains the same. We
discuss
MySQL Connector Python
Throughout this chapter.
PYTHON INTEGRATION WITH MYSQL
MYSQL CONNECTOR PYTHON
PYTHON INTEGRATION WITH MYSQL
What is MYSQL Connector Python?
MYSQL Connector Python is module
or library available in python to
communicate with a MySQL
MYSQL CONNECTOR PYTHON
PYTHON INTEGRATION WITH MYSQL
ADVANTAGES OF MYSQL CONNECTOR PYTHON
PYTHON INTEGRATION WITH MYSQL
 MySQL Connector Python is written in pure
Python, and it is self-sufficient to execute
database queries through python.
It is an official Oracle-supported driver to
work with MySQL and python.
It is Python 3 compatible, actively
maintained.
ADVANTAGES OF MYSQL CONNECTOR PYTHON
MYSQL CONNECTOR PYTHON
INSTALLATION : MYSQL CONNECTOR PYTHON
PREREQUISITES
You need root or administrator privileges to perform
the installation process.
Python must installed on your machine.
Note: – MySQL Connector Python requires python to be
in the system’s PATH. Installation fails if it doesn’t find
Python.
On Unix and Unix-like systems, Python generally
located in a directory included in the default PATH
setting.
On Windows, If Python doesn’t exist in the system’s
PATH, please manually add the directory containing
python.exe yourself.
PLATFORM
PLATFORM
Platform(s): 64-bit Windows, Windows 10, Windows
7, Windows 8, Windows Vista, Windows XP, Linux,
Ubuntu Linux, Debian Linux, SUSE Linux, Red Hat Linux,
Fedora, MacOs.
Python version(s): Python 2 and 3 and above.
MySQL Version(s): Greater than 4.1
WAYS TO INSTALL MySQL Connector Python
WAYS TO INSTALL MySQL Connector Python
There are multiple ways to install Oracle’s
MySQL Connector Python on your machine.
Following are the few ways.
Install MySQL Connector Python using the pip
command.
Install MySQL connector python via source
code (via ZIP or TAR file)
WAYS TO INSTALL MySQL Connector Python
Use Built Distribution A package created in
the native packaging format intended for a
given platform. Example, RPM packages for
Linux or MSI installer for windows.
PIP Command to install MySQL Connector
Python
PIP Command to install MySQL Connector
Python
pip install mysql-connector-python
If you are facing any problem while installing,
please mention the version of the module and then try
to install again. Refer to the above table to install the
correct version.
pip install mysql-connector-
python==8.0.11
PYTHON MySQL DATABASE CONNECTION
PYTHON MySQL DATABASE CONNECTION
Goals - In this session, you’ll learn:
How to connect MySQL Server and create a
table in MySQL from Python.
Different MySQL Connection arguments we
can use to connect to MySQL.
How to change the MySQL connection
timeout when connecting through Python.
ARGUMENTS REQUIRED TO CONNECT MYSQL
FROM PYTHON
ARGUMENTS REQUIRED TO CONNECT MYSQL
FROM PYTHON
You need to know the following detail of the
MySQL server to perform the connection from
Python.
Username – i.e., the username that you use
to work with MySQL Server. The default
username for the MySQL database is a root
Password – Password is given by the user at
the time of installing the mysql database. If you
are using root then you won’t need the
password.
ARGUMENTS REQUIRED TO CONNECT MYSQL
FROM PYTHON
Host Name – is the server name or Ip address
on which MySQL is running. if you are running
on localhost, then you can use localhost, or it’s
IP, i.e. 127.0.0.0
Database Name – Database name to which
you want to connect.
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
Install MySQL Connector Python using pip.
Use the mysql.connector.connect() method
of MySQL Connector Python with required
parameters to connect MySQL.
Use the connection object returned by
a connect() method to create a cursor object to
perform Database Operations.
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
The cursor.execute() to execute SQL queries
from Python.
Close the Cursor object using
a cursor.close() and MySQL database connection
using connection.close() after your work
completes.
Catch Exception if any that may occur during
this process.
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
Follow the steps:-
Step 1: Start the Python
Step 2: Import Package
Step 3: Open Connection or Connect to
database
Step 4: Create a cursor
Step 5: Execute Query
Step 6 Extract data from the result set
Step 7. Close the connection or clean up the
environment.
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
Step 1: Start the Python
Start the Python IDLE editor to write the
script
Step 2: Import MySQL Connector Python
Package.
import mysql.connector
Or
import mysql.connetor as SQLCon
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
Step 3: Open Connection or Connect to
database.
Mycon=mysql.connector.connect(
host='localhost',
database='mysql',
user='root',
password='')
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
Step 3: Open Connection or Connect to
database.
Mycon=mysql.connector.connect(
host='localhost',
database='mysql',
user='root',
password='')
Mycon is a connection object
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
What is Database Connection Object?
A Database connection object controls the
connection to the database. It represents a
unique session with a database connected from
within a script or program
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
One can check the connection by writing
the following code.
If mycon.is_connected():
print(“Successfully Connected”)
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
What is cursor?
A database cursor is a special control
structure that facilitates the row by
processing of records in the result set.
What is result set?
Result set refers to the logical set of
records that are fetched from the database
by executing an SQL query. It is the set of
records retrieved as per the query.
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
Step 4: Create a cursor.
Cursor object=
connectionobject.cursor()
For example:
EmpCursor = mycon.cursor()
Mycon is a connection object
Cursor Object
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
Step 5: Execute Query
EmpCursor.execute(“select * from
emp”)
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
Step 6: Extract data from the result set.
After retrieving the records from the
DB using SQL Select Query. You need to extract
records from the result set.
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
You can extract the result set using any of
the following fetch functions/ cursor methods.
.fetchone() .fetchall()
.fetchmany(n)
.close()
Cursor other methods are: -
.callproc() .nextset()
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
.fetchone()
1
Fetch the next row of a query result set,
returning a single sequence, or None when no
more data is available
Data=EmpCursor.fetchone()
V_count=EmpCursor.rowcount
print(“Total Rows retrieved : “,V_count)
print(data)
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
.fetchmany(n)
2
Fetch many(n) method will return only the
n number of rows from the result set in the
form of tuple containing the records.
Data=empcursor.fetchmany(4)
V_count=EmpCursor.rowcount
print(“Total Rows retrieved : “,V_count)
for row in data:
print(row)
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
.fetchall()
3
Fetch all method will return all the rows
from the result set in the form of tuple
containing the records.
Data=EmpCursor.fetchall()
V_count=EmpCursor.rowcount
print(“Total Rows retrieved : “,V_count)
for row in data:
print(row)
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
Step 7. Close the connection or clean up the
environment.
Syntax:
Connectionobject.close()
Example:
Mycon.close()
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
Python Program to Create Table
import mysql.connector as mysql
db = mysql.connect( host = "localhost", user =
"root", passwd = "dbms", database =
“Employee2019" )
cursor = db.cursor()
cursor.execute("CREATE TABLE users (name
VARCHAR(255), user_name VARCHAR(255))")
CREATING TABLE - PYTHON PROGRAM
Python Program to Create Table
import mysql.connector as mysql
db = mysql.connect( host = "localhost", user =
"root", passwd = "dbms", database =
“Emp2019" )
cursor = db.cursor()
cursor.execute("CREATE TABLE users (name
VARCHAR(255), user_name VARCHAR(255))")
CREATING TABLE - PYTHON PROGRAM
SHOW ALL TABLES - PYTHON PROGRAM
Python Program to show all tables.
import mysql.connector as mysql
db = mysql.connect( host = "localhost", user =
"root", passwd = "", database = “Emp2019" )
cursor = db.cursor()
cursor.execute("SHOW TABLES")
tables = cursor.fetchall()
for table in tables:
print(table)
SHOW ALL TABLES - PYTHON PROGRAM
PARAMETERISED QUERIES
PARAMETERISED QUERIES
You can run the queries with parameters
For example:
V_marks=56
Select * from student where marks>v_marks
These kind of queries are called as
parameterised queries.
PARAMETERISED QUERIES
FORMING QUERY STRINGS
To form a parameterised queries there are
two methods.
FORMING QUERY STRINGS
1. % formatting – (OLD STYLE)
2. .format() – (NEW STYLE )
FORMING QUERY STRINGS
1. % formatting – (OLD STYLE)
S= “Select * from emp where empid=%s
and dept=‘%s’ “ % ( 1006 , ‘Biotech’)
Example 2: Another Method to use %s :-
Ram=8
Id=2
Input=(ram,id)
Qry= “Update comp set ram=%s where id=%s”
Cursor.execute(Qry,input)
FORMING QUERY STRINGS
1. % formatting – (OLD STYLE)
The string formatting uses the following
style:
f % v
Where f is the string template and
v is the value.
For example:
S=“SELECT * FROM STUDENT WHERE
MARKS>%s” %(70,) v
FORMING QUERY STRINGS
2. .format() – (NEW STYLE )
New style of creating SQL Query stringss
involves the use of .format() method of the str
type.
“We have {0} hectares planted to {1}”
.format(49,”Okra”)
Resultant string will be:
“We have 49 hectares planted to okra”
Contd…
FORMING QUERY STRINGS
2. .format() – (NEW STYLE )
SQL_St=“Select * from student where
makrs>{} and section=‘{}’ “ .format(70,’B’)
After execution SQL_St variable stores:-
“Select * from student where marks >70 and
section=‘B’
INSERT AND UPDATE QUERIES
INSERT AND UPDATE QUERIES
INSERT QUERY
INSERT AND UPDATE QUERIES
INSERT QUERY
To Insert a record in a table use cursor
object. When you perform insert or update
remember to commit the transaction.
MyQuery=“Insert into student ( rollno,name,
marks) values ({},’{}’,{} ) “
.format(1203,’Raman’,67.6)
Cursor.execute(MyQuery)
Mycon.execute()
INSERT AND UPDATE QUERIES
UPDATE QUERY
INSERT AND UPDATE QUERIES
To Update a record in a table use cursor
object. When you perform insert or update
remember to commit the transaction.
MyQuery=“update student set marks={}“ where
marks={}” .format(84,66)
Cursor.execute(MyQuery)
Mycon.execute()
UPDATE QUERY
ThankYou

More Related Content

Similar to Chapter 6 Interface Python with MYSQL.pptx

Python Programming Part 8 - MYSQL.pptx
Python Programming Part 8 - MYSQL.pptxPython Programming Part 8 - MYSQL.pptx
Python Programming Part 8 - MYSQL.pptxpercivalfernandez2
 
Python - db.pptx
Python - db.pptxPython - db.pptx
Python - db.pptxRAGAVIC2
 
Online Fitness Gym Documentation
Online Fitness Gym Documentation Online Fitness Gym Documentation
Online Fitness Gym Documentation Abhishek Patel
 
Integration Microservices
Integration MicroservicesIntegration Microservices
Integration MicroservicesKasun Indrasiri
 
Www Kitebird Com Articles Pydbapi Html Toc 1
Www Kitebird Com Articles Pydbapi Html Toc 1Www Kitebird Com Articles Pydbapi Html Toc 1
Www Kitebird Com Articles Pydbapi Html Toc 1AkramWaseem
 
Python Database Connection | Edureka
Python Database Connection | EdurekaPython Database Connection | Edureka
Python Database Connection | EdurekaEdureka!
 
Apponix Python Full stack Training course
Apponix Python Full stack Training courseApponix Python Full stack Training course
Apponix Python Full stack Training course056kevinChauhan
 
Socket programming-in-python
Socket programming-in-pythonSocket programming-in-python
Socket programming-in-pythonYuvaraja Ravi
 
report on internshala python training
 report on internshala python  training  report on internshala python  training
report on internshala python training surabhimalviya1
 
The power of mysqlnd plugins
The power of mysqlnd pluginsThe power of mysqlnd plugins
The power of mysqlnd pluginsUlf Wendel
 
Interfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptxInterfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptxcavicav231
 
MySQL Enterprise Edition
MySQL Enterprise EditionMySQL Enterprise Edition
MySQL Enterprise EditionMySQL Brasil
 
Rapid Web Development with Python for Absolute Beginners
Rapid Web Development with Python for Absolute BeginnersRapid Web Development with Python for Absolute Beginners
Rapid Web Development with Python for Absolute BeginnersFatih Karatana
 
Connect JavaEE to the cloud with JCA by Steve Millidge
Connect JavaEE to the cloud with JCA by Steve MillidgeConnect JavaEE to the cloud with JCA by Steve Millidge
Connect JavaEE to the cloud with JCA by Steve MillidgePayara
 
Exploring Five Lesser-Known Python Libraries
Exploring Five Lesser-Known Python LibrariesExploring Five Lesser-Known Python Libraries
Exploring Five Lesser-Known Python LibrariesMinhazulAbedin27
 

Similar to Chapter 6 Interface Python with MYSQL.pptx (20)

Python Programming Part 8 - MYSQL.pptx
Python Programming Part 8 - MYSQL.pptxPython Programming Part 8 - MYSQL.pptx
Python Programming Part 8 - MYSQL.pptx
 
Python - mySOL
Python - mySOLPython - mySOL
Python - mySOL
 
Python - db.pptx
Python - db.pptxPython - db.pptx
Python - db.pptx
 
Chapter -7.pptx
Chapter -7.pptxChapter -7.pptx
Chapter -7.pptx
 
Pydbapi
PydbapiPydbapi
Pydbapi
 
Online Fitness Gym Documentation
Online Fitness Gym Documentation Online Fitness Gym Documentation
Online Fitness Gym Documentation
 
Python
Python Python
Python
 
Integration Microservices
Integration MicroservicesIntegration Microservices
Integration Microservices
 
Www Kitebird Com Articles Pydbapi Html Toc 1
Www Kitebird Com Articles Pydbapi Html Toc 1Www Kitebird Com Articles Pydbapi Html Toc 1
Www Kitebird Com Articles Pydbapi Html Toc 1
 
Python Database Connection | Edureka
Python Database Connection | EdurekaPython Database Connection | Edureka
Python Database Connection | Edureka
 
Apponix Python Full stack Training course
Apponix Python Full stack Training courseApponix Python Full stack Training course
Apponix Python Full stack Training course
 
Socket programming-in-python
Socket programming-in-pythonSocket programming-in-python
Socket programming-in-python
 
report on internshala python training
 report on internshala python  training  report on internshala python  training
report on internshala python training
 
The power of mysqlnd plugins
The power of mysqlnd pluginsThe power of mysqlnd plugins
The power of mysqlnd plugins
 
Interfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptxInterfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptx
 
MySQL Enterprise Edition
MySQL Enterprise EditionMySQL Enterprise Edition
MySQL Enterprise Edition
 
{py}gradle
{py}gradle{py}gradle
{py}gradle
 
Rapid Web Development with Python for Absolute Beginners
Rapid Web Development with Python for Absolute BeginnersRapid Web Development with Python for Absolute Beginners
Rapid Web Development with Python for Absolute Beginners
 
Connect JavaEE to the cloud with JCA by Steve Millidge
Connect JavaEE to the cloud with JCA by Steve MillidgeConnect JavaEE to the cloud with JCA by Steve Millidge
Connect JavaEE to the cloud with JCA by Steve Millidge
 
Exploring Five Lesser-Known Python Libraries
Exploring Five Lesser-Known Python LibrariesExploring Five Lesser-Known Python Libraries
Exploring Five Lesser-Known Python Libraries
 

Recently uploaded

Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral AnalysisRaman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral AnalysisDiwakar Mishra
 
A relative description on Sonoporation.pdf
A relative description on Sonoporation.pdfA relative description on Sonoporation.pdf
A relative description on Sonoporation.pdfnehabiju2046
 
Artificial Intelligence In Microbiology by Dr. Prince C P
Artificial Intelligence In Microbiology by Dr. Prince C PArtificial Intelligence In Microbiology by Dr. Prince C P
Artificial Intelligence In Microbiology by Dr. Prince C PPRINCE C P
 
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCESTERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCEPRINCE C P
 
Formation of low mass protostars and their circumstellar disks
Formation of low mass protostars and their circumstellar disksFormation of low mass protostars and their circumstellar disks
Formation of low mass protostars and their circumstellar disksSérgio Sacani
 
Chemistry 4th semester series (krishna).pdf
Chemistry 4th semester series (krishna).pdfChemistry 4th semester series (krishna).pdf
Chemistry 4th semester series (krishna).pdfSumit Kumar yadav
 
Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Nistarini College, Purulia (W.B) India
 
TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...
TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...
TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...ssifa0344
 
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service 🪡
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service  🪡CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service  🪡
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service 🪡anilsa9823
 
Zoology 4th semester series (krishna).pdf
Zoology 4th semester series (krishna).pdfZoology 4th semester series (krishna).pdf
Zoology 4th semester series (krishna).pdfSumit Kumar yadav
 
Orientation, design and principles of polyhouse
Orientation, design and principles of polyhouseOrientation, design and principles of polyhouse
Orientation, design and principles of polyhousejana861314
 
Pests of cotton_Sucking_Pests_Dr.UPR.pdf
Pests of cotton_Sucking_Pests_Dr.UPR.pdfPests of cotton_Sucking_Pests_Dr.UPR.pdf
Pests of cotton_Sucking_Pests_Dr.UPR.pdfPirithiRaju
 
SOLUBLE PATTERN RECOGNITION RECEPTORS.pptx
SOLUBLE PATTERN RECOGNITION RECEPTORS.pptxSOLUBLE PATTERN RECOGNITION RECEPTORS.pptx
SOLUBLE PATTERN RECOGNITION RECEPTORS.pptxkessiyaTpeter
 
Recombinant DNA technology (Immunological screening)
Recombinant DNA technology (Immunological screening)Recombinant DNA technology (Immunological screening)
Recombinant DNA technology (Immunological screening)PraveenaKalaiselvan1
 
Isotopic evidence of long-lived volcanism on Io
Isotopic evidence of long-lived volcanism on IoIsotopic evidence of long-lived volcanism on Io
Isotopic evidence of long-lived volcanism on IoSérgio Sacani
 
Green chemistry and Sustainable development.pptx
Green chemistry  and Sustainable development.pptxGreen chemistry  and Sustainable development.pptx
Green chemistry and Sustainable development.pptxRajatChauhan518211
 
Animal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptxAnimal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptxUmerFayaz5
 
Hubble Asteroid Hunter III. Physical properties of newly found asteroids
Hubble Asteroid Hunter III. Physical properties of newly found asteroidsHubble Asteroid Hunter III. Physical properties of newly found asteroids
Hubble Asteroid Hunter III. Physical properties of newly found asteroidsSérgio Sacani
 

Recently uploaded (20)

Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral AnalysisRaman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
 
A relative description on Sonoporation.pdf
A relative description on Sonoporation.pdfA relative description on Sonoporation.pdf
A relative description on Sonoporation.pdf
 
Artificial Intelligence In Microbiology by Dr. Prince C P
Artificial Intelligence In Microbiology by Dr. Prince C PArtificial Intelligence In Microbiology by Dr. Prince C P
Artificial Intelligence In Microbiology by Dr. Prince C P
 
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCESTERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
 
Formation of low mass protostars and their circumstellar disks
Formation of low mass protostars and their circumstellar disksFormation of low mass protostars and their circumstellar disks
Formation of low mass protostars and their circumstellar disks
 
Chemistry 4th semester series (krishna).pdf
Chemistry 4th semester series (krishna).pdfChemistry 4th semester series (krishna).pdf
Chemistry 4th semester series (krishna).pdf
 
Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...
 
TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...
TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...
TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...
 
Engler and Prantl system of classification in plant taxonomy
Engler and Prantl system of classification in plant taxonomyEngler and Prantl system of classification in plant taxonomy
Engler and Prantl system of classification in plant taxonomy
 
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service 🪡
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service  🪡CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service  🪡
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service 🪡
 
Zoology 4th semester series (krishna).pdf
Zoology 4th semester series (krishna).pdfZoology 4th semester series (krishna).pdf
Zoology 4th semester series (krishna).pdf
 
Orientation, design and principles of polyhouse
Orientation, design and principles of polyhouseOrientation, design and principles of polyhouse
Orientation, design and principles of polyhouse
 
Pests of cotton_Sucking_Pests_Dr.UPR.pdf
Pests of cotton_Sucking_Pests_Dr.UPR.pdfPests of cotton_Sucking_Pests_Dr.UPR.pdf
Pests of cotton_Sucking_Pests_Dr.UPR.pdf
 
SOLUBLE PATTERN RECOGNITION RECEPTORS.pptx
SOLUBLE PATTERN RECOGNITION RECEPTORS.pptxSOLUBLE PATTERN RECOGNITION RECEPTORS.pptx
SOLUBLE PATTERN RECOGNITION RECEPTORS.pptx
 
9953056974 Young Call Girls In Mahavir enclave Indian Quality Escort service
9953056974 Young Call Girls In Mahavir enclave Indian Quality Escort service9953056974 Young Call Girls In Mahavir enclave Indian Quality Escort service
9953056974 Young Call Girls In Mahavir enclave Indian Quality Escort service
 
Recombinant DNA technology (Immunological screening)
Recombinant DNA technology (Immunological screening)Recombinant DNA technology (Immunological screening)
Recombinant DNA technology (Immunological screening)
 
Isotopic evidence of long-lived volcanism on Io
Isotopic evidence of long-lived volcanism on IoIsotopic evidence of long-lived volcanism on Io
Isotopic evidence of long-lived volcanism on Io
 
Green chemistry and Sustainable development.pptx
Green chemistry  and Sustainable development.pptxGreen chemistry  and Sustainable development.pptx
Green chemistry and Sustainable development.pptx
 
Animal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptxAnimal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptx
 
Hubble Asteroid Hunter III. Physical properties of newly found asteroids
Hubble Asteroid Hunter III. Physical properties of newly found asteroidsHubble Asteroid Hunter III. Physical properties of newly found asteroids
Hubble Asteroid Hunter III. Physical properties of newly found asteroids
 

Chapter 6 Interface Python with MYSQL.pptx

  • 1. CHAPTER - XVI INTERFACE PYTHON WITH MYSQL
  • 4. INTRODUCTION Every organisation depends on large databases. These are essentially collections of tables, and’ connected with each other through columns. These database systems support SQL, the Structured Query Language, which is used to create, access and manipulate the data.
  • 5. INTRODUCTION The Python programming language has powerful features for database programming. Python supports various databases like MySQL, Oracle, Sybase, PostgreSQL, etc. Python also supports Data Definition Language (DDL), Data Manipulation Language (DML) and Data Query Statements.
  • 6. INTRODUCTION For database programming, the Python DB API is a widely used module that provides a database application programming interface.
  • 8. INTERFACE What is an Interface? Interface is the way for an application to interact with certain system/application.
  • 10. API - APPLICATION PROGRAMMING INTERFACE
  • 11. API -APPLICATION PROGRAMMING INTERFACE In computer programming, an application programming interface is a set of subroutine definitions, communication protocols, and tools for building software. In general terms, it is a set of clearly defined methods of communication among various components.
  • 12. Consider an API as a waiter in a restaurant. Suppose you have a menu of your favourite food and the kitchen is the system where your order is made. But how do you take your order till the kitchen? Correct, you call a waiter, give him/her the order, which in turns takes your order till the kitchen and then your order is made there and then finally, the waiter comes back with your delicious ordered food. API -APPLICATION PROGRAMMING INTERFACE
  • 13. Thus, the API is very much similar to the waiter. API is the messenger that takes your order(waiter) and tells the system(kitchen) what to do (to prepare food) and in return gives back the response you asked for (waiter returns with the ordered food). API -APPLICATION PROGRAMMING INTERFACE
  • 14. BENEFITS OF PYTHON FOR DATABASE PROGRAMMING
  • 15. There are many good reasons to use Python for programming database applications: Programming in Python is arguably more efficient and faster compared to other languages. Python is famous for its portability. It is platform independent. BENEFITS OF PYTHON FOR DATABASE PROGRAMMING
  • 16. Python supports SQL cursors. In many programming languages, the application developer needs to take care of the open and closed connections of the database, to avoid further exceptions and errors. In Python, these connections are taken care of. BENEFITS OF PYTHON FOR DATABASE PROGRAMMING
  • 17. Python supports relational database systems. Python database APIs are compatible with various databases, so it is very easy to migrate and port database application interfaces. BENEFITS OF PYTHON FOR DATABASE PROGRAMMING
  • 19. PYTHON INTEGRATION WITH MYSQL We discuss how to develop and integrate Python applications that work with a MySQL database server. Python is dynamic, and enterprise language and it has all the support to build large and complex enterprise applications. MySQL is the world’s most powerful and used open-source database provided by Oracle. INTRODUCTION
  • 20. PYTHON INTEGRATION WITH MYSQL PYTHON MODULE FOR COMMUNICATING WITH MYSQL
  • 21. PYTHON INTEGRATION WITH MYSQL Total 5 modules available in python to communicate with a MySQL and provides MySQL database support to our applications and they are:- 1. MySQL Connector Python 2. PyMySQL 3. MySQLDB 4. mysqlclient 5. OurSQL
  • 22. PYTHON INTEGRATION WITH MYSQL Note: Above all interfaces or modules are adhere to Python Database API Specification v2.0 (PEP 249) that means the syntax, method and the way of access database is the same in all. PEP 249 has been designed to encourage and maintain similarity between the Python modules that are used to access databases. By doing this, above all modules are following rules defined in Python Database API Specification v2.0 (PEP 249).
  • 23. PYTHON INTEGRATION WITH MYSQL You can choose any of the above modules as per your requirement. The way of accessing the MySQL database remains the same. We discuss MySQL Connector Python Throughout this chapter.
  • 24. PYTHON INTEGRATION WITH MYSQL MYSQL CONNECTOR PYTHON
  • 25. PYTHON INTEGRATION WITH MYSQL What is MYSQL Connector Python? MYSQL Connector Python is module or library available in python to communicate with a MySQL MYSQL CONNECTOR PYTHON
  • 26. PYTHON INTEGRATION WITH MYSQL ADVANTAGES OF MYSQL CONNECTOR PYTHON
  • 27. PYTHON INTEGRATION WITH MYSQL  MySQL Connector Python is written in pure Python, and it is self-sufficient to execute database queries through python. It is an official Oracle-supported driver to work with MySQL and python. It is Python 3 compatible, actively maintained. ADVANTAGES OF MYSQL CONNECTOR PYTHON
  • 29. INSTALLATION : MYSQL CONNECTOR PYTHON
  • 30. PREREQUISITES You need root or administrator privileges to perform the installation process. Python must installed on your machine. Note: – MySQL Connector Python requires python to be in the system’s PATH. Installation fails if it doesn’t find Python. On Unix and Unix-like systems, Python generally located in a directory included in the default PATH setting. On Windows, If Python doesn’t exist in the system’s PATH, please manually add the directory containing python.exe yourself.
  • 32. PLATFORM Platform(s): 64-bit Windows, Windows 10, Windows 7, Windows 8, Windows Vista, Windows XP, Linux, Ubuntu Linux, Debian Linux, SUSE Linux, Red Hat Linux, Fedora, MacOs. Python version(s): Python 2 and 3 and above. MySQL Version(s): Greater than 4.1
  • 33. WAYS TO INSTALL MySQL Connector Python
  • 34. WAYS TO INSTALL MySQL Connector Python There are multiple ways to install Oracle’s MySQL Connector Python on your machine. Following are the few ways. Install MySQL Connector Python using the pip command. Install MySQL connector python via source code (via ZIP or TAR file)
  • 35. WAYS TO INSTALL MySQL Connector Python Use Built Distribution A package created in the native packaging format intended for a given platform. Example, RPM packages for Linux or MSI installer for windows.
  • 36. PIP Command to install MySQL Connector Python
  • 37. PIP Command to install MySQL Connector Python pip install mysql-connector-python If you are facing any problem while installing, please mention the version of the module and then try to install again. Refer to the above table to install the correct version. pip install mysql-connector- python==8.0.11
  • 38. PYTHON MySQL DATABASE CONNECTION
  • 39. PYTHON MySQL DATABASE CONNECTION Goals - In this session, you’ll learn: How to connect MySQL Server and create a table in MySQL from Python. Different MySQL Connection arguments we can use to connect to MySQL. How to change the MySQL connection timeout when connecting through Python.
  • 40. ARGUMENTS REQUIRED TO CONNECT MYSQL FROM PYTHON
  • 41. ARGUMENTS REQUIRED TO CONNECT MYSQL FROM PYTHON You need to know the following detail of the MySQL server to perform the connection from Python. Username – i.e., the username that you use to work with MySQL Server. The default username for the MySQL database is a root Password – Password is given by the user at the time of installing the mysql database. If you are using root then you won’t need the password.
  • 42. ARGUMENTS REQUIRED TO CONNECT MYSQL FROM PYTHON Host Name – is the server name or Ip address on which MySQL is running. if you are running on localhost, then you can use localhost, or it’s IP, i.e. 127.0.0.0 Database Name – Database name to which you want to connect.
  • 43. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python
  • 44. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python Install MySQL Connector Python using pip. Use the mysql.connector.connect() method of MySQL Connector Python with required parameters to connect MySQL. Use the connection object returned by a connect() method to create a cursor object to perform Database Operations.
  • 45. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python The cursor.execute() to execute SQL queries from Python. Close the Cursor object using a cursor.close() and MySQL database connection using connection.close() after your work completes. Catch Exception if any that may occur during this process.
  • 46. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python
  • 47. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python Follow the steps:- Step 1: Start the Python Step 2: Import Package Step 3: Open Connection or Connect to database Step 4: Create a cursor Step 5: Execute Query Step 6 Extract data from the result set Step 7. Close the connection or clean up the environment.
  • 48. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python Step 1: Start the Python Start the Python IDLE editor to write the script Step 2: Import MySQL Connector Python Package. import mysql.connector Or import mysql.connetor as SQLCon
  • 49. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python Step 3: Open Connection or Connect to database. Mycon=mysql.connector.connect( host='localhost', database='mysql', user='root', password='')
  • 50. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python Step 3: Open Connection or Connect to database. Mycon=mysql.connector.connect( host='localhost', database='mysql', user='root', password='') Mycon is a connection object
  • 51. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python What is Database Connection Object? A Database connection object controls the connection to the database. It represents a unique session with a database connected from within a script or program
  • 52. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python One can check the connection by writing the following code. If mycon.is_connected(): print(“Successfully Connected”)
  • 53. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python What is cursor? A database cursor is a special control structure that facilitates the row by processing of records in the result set. What is result set? Result set refers to the logical set of records that are fetched from the database by executing an SQL query. It is the set of records retrieved as per the query.
  • 54. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python Step 4: Create a cursor. Cursor object= connectionobject.cursor() For example: EmpCursor = mycon.cursor() Mycon is a connection object Cursor Object
  • 55. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python Step 5: Execute Query EmpCursor.execute(“select * from emp”)
  • 56. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python Step 6: Extract data from the result set. After retrieving the records from the DB using SQL Select Query. You need to extract records from the result set.
  • 57. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python You can extract the result set using any of the following fetch functions/ cursor methods. .fetchone() .fetchall() .fetchmany(n) .close() Cursor other methods are: - .callproc() .nextset()
  • 58. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python .fetchone() 1 Fetch the next row of a query result set, returning a single sequence, or None when no more data is available Data=EmpCursor.fetchone() V_count=EmpCursor.rowcount print(“Total Rows retrieved : “,V_count) print(data)
  • 59. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python .fetchmany(n) 2 Fetch many(n) method will return only the n number of rows from the result set in the form of tuple containing the records. Data=empcursor.fetchmany(4) V_count=EmpCursor.rowcount print(“Total Rows retrieved : “,V_count) for row in data: print(row)
  • 60. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python .fetchall() 3 Fetch all method will return all the rows from the result set in the form of tuple containing the records. Data=EmpCursor.fetchall() V_count=EmpCursor.rowcount print(“Total Rows retrieved : “,V_count) for row in data: print(row)
  • 61. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python Step 7. Close the connection or clean up the environment. Syntax: Connectionobject.close() Example: Mycon.close()
  • 62. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python Python Program to Create Table import mysql.connector as mysql db = mysql.connect( host = "localhost", user = "root", passwd = "dbms", database = “Employee2019" ) cursor = db.cursor() cursor.execute("CREATE TABLE users (name VARCHAR(255), user_name VARCHAR(255))")
  • 63. CREATING TABLE - PYTHON PROGRAM
  • 64. Python Program to Create Table import mysql.connector as mysql db = mysql.connect( host = "localhost", user = "root", passwd = "dbms", database = “Emp2019" ) cursor = db.cursor() cursor.execute("CREATE TABLE users (name VARCHAR(255), user_name VARCHAR(255))") CREATING TABLE - PYTHON PROGRAM
  • 65. SHOW ALL TABLES - PYTHON PROGRAM
  • 66. Python Program to show all tables. import mysql.connector as mysql db = mysql.connect( host = "localhost", user = "root", passwd = "", database = “Emp2019" ) cursor = db.cursor() cursor.execute("SHOW TABLES") tables = cursor.fetchall() for table in tables: print(table) SHOW ALL TABLES - PYTHON PROGRAM
  • 68. PARAMETERISED QUERIES You can run the queries with parameters For example: V_marks=56 Select * from student where marks>v_marks These kind of queries are called as parameterised queries.
  • 70. To form a parameterised queries there are two methods. FORMING QUERY STRINGS 1. % formatting – (OLD STYLE) 2. .format() – (NEW STYLE )
  • 71. FORMING QUERY STRINGS 1. % formatting – (OLD STYLE) S= “Select * from emp where empid=%s and dept=‘%s’ “ % ( 1006 , ‘Biotech’) Example 2: Another Method to use %s :- Ram=8 Id=2 Input=(ram,id) Qry= “Update comp set ram=%s where id=%s” Cursor.execute(Qry,input)
  • 72. FORMING QUERY STRINGS 1. % formatting – (OLD STYLE) The string formatting uses the following style: f % v Where f is the string template and v is the value. For example: S=“SELECT * FROM STUDENT WHERE MARKS>%s” %(70,) v
  • 73. FORMING QUERY STRINGS 2. .format() – (NEW STYLE ) New style of creating SQL Query stringss involves the use of .format() method of the str type. “We have {0} hectares planted to {1}” .format(49,”Okra”) Resultant string will be: “We have 49 hectares planted to okra” Contd…
  • 74. FORMING QUERY STRINGS 2. .format() – (NEW STYLE ) SQL_St=“Select * from student where makrs>{} and section=‘{}’ “ .format(70,’B’) After execution SQL_St variable stores:- “Select * from student where marks >70 and section=‘B’
  • 75. INSERT AND UPDATE QUERIES
  • 76. INSERT AND UPDATE QUERIES INSERT QUERY
  • 77. INSERT AND UPDATE QUERIES INSERT QUERY To Insert a record in a table use cursor object. When you perform insert or update remember to commit the transaction. MyQuery=“Insert into student ( rollno,name, marks) values ({},’{}’,{} ) “ .format(1203,’Raman’,67.6) Cursor.execute(MyQuery) Mycon.execute()
  • 78. INSERT AND UPDATE QUERIES UPDATE QUERY
  • 79. INSERT AND UPDATE QUERIES To Update a record in a table use cursor object. When you perform insert or update remember to commit the transaction. MyQuery=“update student set marks={}“ where marks={}” .format(84,66) Cursor.execute(MyQuery) Mycon.execute() UPDATE QUERY