0% found this document useful (0 votes)
317 views40 pages

Interface Python With MySQL

The document discusses connecting a Python application to a MySQL database. It describes installing the mysql.connector package to provide connectivity between Python and MySQL. It then outlines the steps to connect a Python program to MySQL, which include importing mysql.connector, opening a connection, creating a cursor, executing queries, extracting data from the result set, and closing the connection."

Uploaded by

apple
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
317 views40 pages

Interface Python With MySQL

The document discusses connecting a Python application to a MySQL database. It describes installing the mysql.connector package to provide connectivity between Python and MySQL. It then outlines the steps to connect a Python program to MySQL, which include importing mysql.connector, opening a connection, creating a cursor, executing queries, extracting data from the result set, and closing the connection."

Uploaded by

apple
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 40

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.
❑ Interacting with a database is an important feature in many
programming languages including python.

❑ When we design real life applications, in comparison to


storing data in flat files, its much easier to store, retrieve and
modify data in a database. We have a situation in which we
need to manipulate the data stored in the database through
the application designed by us.
Introduction
❑ For example, an application is designed using Python and it
has to be connected to the MySQL database from within
the Python Script.

❑ To connect to a database from within Python, a library is


required which provides connectivity.

❑ 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

❑ We are going to use mysql connector library to interface


python with MySQL.
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
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
Step 1: Start Python
Start Python’s editor where we are going to create
Python scripts. It can be IDLE or any editor.
Step 2: Import mysql. connector Package
import mysql.connector

Or Any valid
identifier

import mysql.connector as ms

Here “ms” is an alias, so every time we can use “ms” in


place of “mysql.connector”
Step 3 : Open a Connection to MySQL Database

 To create connection, connect() function is used


 Its syntax is:

<connection object>= mysql.connector.connect (host=<host-


name>,user=<username>, 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 “admin”
 Database is the name of database whose data(table) we want to
use
Step 3 : Open a Connection to MySQL Database -
USING CONNECT ()
import mysql.connector
mycon=mysql.connector.connect(host="localhost",user="root",
passwd=“admin",database=“company")
(or)
import mysql.connector as mys
mycon=mys.connect(host=“localhost”,user=“root”,passwd=“admin”,
database=“company”)

The above commands will establish the connection to MYSQL


database with user as “root”, Password as ”admin” and to the
MYSQL database namely “company” which exists in MYSQL.
A database connection object controls the connection to the
database.
Step 3 : Open a Connection to MySQL
Database - CHECKING FOR CONNECTION
If Python reports no error, then we have successfully
connected to the MYSQL database.
To check for connection we can use the function is_connected()
which returns True, if connection is successful.

Example :

if mycon.is_connected():
print(“Successfully connected to MYSQL database”)
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
Step 4: 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 the connection in
one go.
 We may want to access data one row at a time, but
query processing cannot happen as one row at a time,
so cursor helps 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.
Step 4: Create a Cursor Instance

To create an instance of cursor we use cursor()


Syntax :
<cursor object>=<connection object>.cursor()
Example:
cursor=mycon.cursor()

mycon is the connection object through which we established connection to the


MYSQL database, the same connection object is used to create the cursor
instance.
Step 5 : Execute SQL Query
❑ CREATE CURSOR
❑ mycursor = mycon.cursor()
❑ TO EXECUTE QUERY
❑ We use execute() function to send query to connection

❑ SYNTAX

Cursor_name.execute(query)
For e.g.
mycursor.execute(“ create table emp(empno
int,name varchar(30),dept varchar(30),salary float)” )
Example: To create a table in mysql through python code

Example: To insert rows into emp table in mysql through python code
Table to work (emp)
Example: To see the content of the table

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
Step 6: Extract Data from Resultset

The records retrieved from the database are stored


in the cursor object as a result set and we can extract the
data from the result set using any of the following functions.

(i) <data>=<cursor>.fetchall()
(ii) <data>=<cursor>.fetchone()
(iii) <data>=<cursor>.fetchmany(<n>)
(iv) <variable>=<cursor>.rowcount
Step 6:Fetching(extracting) data from ResultSet
 fetchall() : it will return all the records 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 records it will
return None
 fetchmany(n) : it will return n number of records. If no
more records it will return an empty tuple.
 rowcount : it will return number of rows retrieved from
the cursor so far.
Example 1 – fetchall()
Example 2 – fetchall()
Example 3: fetchone()
Example 4: fetchmany(n)
Step 7: Clean Up the Environment

The connection to be closed after all the processing got


over.
Close() is used

Syntax :
<connection_object>.close()

Example:
mycon.close()
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
Concatenating variable with query
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.
String template with %s formatting
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.,
str.format() is one of the string formatting methods in Python3,
which allows multiple substitutions and value formatting. This
method lets us concatenate elements within a string through
positional formatting.
Using a Single Formatter :
Formatters work by putting in one or more replacement fields and
placeholders defined by a pair of curly braces { } into a string and
calling the str.format().
The value we wish to put into the placeholders and concatenate
with the string passed as parameters into the format function.
Syntax : { } .format(value)

Parameters :
(value) : Can be an integer, floating point numeric constant, string,
characters or even variables.
Returntype : Returns a formatted string with the value passed as
parameter in the placeholder position.
Example:

print ("{}, A computer science portal for beginners.".format(“Welcome"))

# using format option for a value stored in a variable

str = "This article is written in {}"


print (str.format("Python"))

# formatting a string using a numeric constant


print ("Hello, I am {} years old !".format(18))

Output :
Welcome, A computer science portal for beginners.
This article is written in Python
Hello, I am 18 years old!
String template with {} and format()
String template with {} and format()

Alternate code :
format(s,d) or format(sales,1)
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()
Example : inserting data BEFORE PROGRAM EXECUTION

AFTER PROGRAM EXECUTION


Example: Updating record
Guess the output

You might also like