Python MySQL Connectivity
1
Here we are using mysql as back end database because it is open
source,free and portable. Any one of the modules either mysql
- connector or MySQLdb can be used for database programming.
1. Mysql-connector enables Python programs to access MySQL databases,
using an API that is compliant with the Python Database API
Specification v2.0.
2. MySQLdb is an interface for connecting to a MySQL database server
from Python. It implements the Python Database API v2.0 and is built
on top of the MySQL C API.
2
We must download a separate DB API (database application programming
interface) module for each database we need to access. Suppose we need to
access an Oracle database as well as a MySQL database, we must download
both the Oracle and the MySQL database modules. The DB API provides a
minimal standard for working with databases using Python structures and
syntax wherever possible. This API includes the following −
● Importing the API module.
● Acquiring a connection with the database.
● Issuing SQL statements and stored procedures.
● Closing the connection
3
To download MySQL Python Connector
MySQL Python Connector is used to access the MySQL
database from Python, you need a database driver. MySQL
Connector/Python is a standardized database driver provided
by MySQL.
Step 1: Open Command window
Step2 : type pip install mysql-connector
4
Now, to check whether mysql-connector is installed/ working properly -
1. Open Python IDLE
2. Type import mysql
3. If no error occurs, it means mysql-connector is working properly
5
Steps to connect a python application to our MySQL database
1. Import mysql.connector module
2. Create the connection object.
3. Create the cursor object
4. Execute the query
6
Some important points are as follows:
• To connect to a database from within a programming
application, you need a framework that facilitates
communication between two different genres of software
(programming application and DBMS).
• To connect from Python to MYSQL, you need a library called
MySQL connector.
• You must import mysql.connector in the Python
program/script before writing code of connectivity.
• Steps to create a database connectivity Python application are:
• Step 1. Start Python: start Python's editor where you can
create your python scripts, i.e; IDE or IDLE. 7
• Step 2. Import the package required for database programming.
• Here you need to import mysql.connector package in your python
scripts.
• Step 3. Open a connection: Here we need to establish a
connection to MYSQL database using connect(). This requires 4
parameters, the syntax for this is as follows:
<Connection_object> = mysql.connector.connect(host=
<host_name>, user=<username>, passwd =<password> , [database
= <database>])
• where user is the user name
• password is the password of the user
• host_name is IP address. database is the database name of mysql
for example:
## import mysql.connector as sqltor
mycon = sqltor.connect(host ="localhost" , user ="root", passwd
= "mypass", database ="test")
• Step 4. Create a cursor instance.
• Here we have to create an instance of cursor by using cursor(),
the syntax for the following is as follows:
• <cursorobject> =<connectionobject>.cursor()
• i.e; in the above connection we can create cursor() by writing:
• cursor = mycon.cursor()
9
• Step 5. Execute a query: here we use the execute() with
following syntax.
• < cursorobject>.execute(<sql query string>)
• cursor.execute("select*from data)
• Step 6. Extract data from result set. Here you can fetch the
data from the resultset by using fetch( ) functions. [fetchall(),
fetchmany(<n>), fetchone()]
• Step 7. Clean up the environment.
• A database Connection object controls the connection to the
database. It represents a unique session with a database
connected from within a script/program.
10
• A Database Cursor is a special control structure that facilitates
the row by row processing of records in the resultset, i.e., the
set of records retrieved as per query.
• The resultset refers to a logical set of records that are fetched
from the database by executing an SQL query and made
available to the application program.
• You can use connect() method for establishing database
connection, cursor() to create a cursor and execute() to
execute an SQL query.
• For INSERT, UPDATE and DELETE queries, you must run
commit() with the connection object.
11
Creating the connection : connect () method
Pass the database details like HostName, username, and the database password in the
method call. The method returns the connection object.
Syntax :
ConnObject = mysql.connector.connect
(host = <hostname>, user = <username> , passwd = <password> )
import mysql.connector
# Open database connection
conn = mysql.connector.connect(host="localhost",user="root",password="DPS@123",
database='test')
#print connector
print (conn)
RESTART: G:\Ritu Data\Class XII Notes(2019-20)\Ritu python \DBC with Mysql 01.py
<mysql.connector.connection_cext.CMySQLConnection object at 0x0000026A758D5F60>
12
Cursor in Python
Cursors are created by the connection.cursor() method. They are bound to
the connection for the entire lifetime of the program and all the commands
are executed in the context of the database session wrapped by the
connection.
<cur_obj> = conn.cursor()
Note : We need cursor to execute our MySQL Queries
13
To display list of available tables in MySQL
With the help of
execute () one can
run any MySQL
query
('bank',)
('dishes',)
('doctors',)
Showing list of tables ('employee',)
('flights',)
('gadget_details',)
14
We can also create our database through python
Creating
Database
See a new
database
('employees',)
employees is
('information_schema',)
('mt1',) created
output ('mysql',)
('performance_schema',)
('sys',)
15
('test',)
Now , let us create a table ‘Employee’
Creating
table
16
Use of desc <table> to view table structure
output
17
Inserting data into table Employee
Inserting
a record
output
18
In the same way, we can insert multiple records
Inserting many
records by creating
list of tuples
Note that here we have to use executemany() instead of
execute()
output
19
Inserting records by taking its input by user
With INSERT INTO statement, we can
mention the format specifier (%s) in
place of values.
20
Deleting record
Employee Name
whose details
needs be deleted
output
21
Functions used with cursor object
• cursor.fetchall() fetches all the rows of a query result. It returns all
the rows as a list of tuples. An empty list is returned if there is no
record to fetch.
• cursor.fetchmany(size) returns the number of rows specified by
size argument. When called repeatedly this method fetches the
next set of rows of a query result and returns a list of tuples. If no
more rows are available, it returns an empty list.
• cursor.fetchone() method returns a single record or None if no
more rows are available.
22
Selecting Records
The resultset refers to a logical set of records that are fetched. Fetchall will return all the
records retrieved as per the query in a tuple form. RowCount will tell display no. of records
fetched after running the query.
Printing no. of records
23
Use of Fetchone
24
Use of Fetchmany
output
25
Updating Records
26
Updating Records based on Dynamic Column names
Set {} and where {}
format substitutes
the values
27
Rules for parameter insertion
"parameter insertion" is meant for only for values, it will not
work for table names, column names, etc. - for those, the Python
string substitution works fine in the sql syntax defintion
28