015. Interface Python with MySQL-Converted copy
015. Interface Python with MySQL-Converted copy
MYSQL
Connecting Python application with
Introductio
n
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
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
Importing
mysql.connector
import mysql.connector
Or
import mysql.connector as ms
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
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. IF
no more record it will return an empty tuple.
Syntax:
rowcount
count : it will return
= cursor.rowcount number
(It is a of rows )retrieved
cursor property
data
AFTER PROGRAM
EXECUTION
Example: Updating
record