MySQL - Python Connectivity
MySQL - Python Connectivity
Connection
Grade 12
Computer Science
CBSE Syllabus:
• Interface of python with an SQL database:
• connecting SQL with Python,
• performing insert, update, delete queries using cursor,
• display data by using connect(), cursor(), execute(), commit(),
fetchone(), fetchall(), rowcount,
• creating database connectivity applications,
• use of %s format specifier or format() to perform queries
Goals of this lesson, in this lesson, 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
Steps to connect MySQL database in Python using MySQL Connector Python
1.2 5.7, 5.6, 5.5 (5.1, 5.0, 4.1) 3.4, 3.3, 3.2, 3.1, 2.7, 2.6
Pip Command to install MySQL Connector python
It is always accessible and straightforward to install any module using pip in
python. MySQL Connector Python is available on pypi.org so you can install
using pip command.
Use the following 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 it again. Refer to the above table to install the
correct version.
pip install mysql-connector-python==8.0.11
An API (Application Programming Interface) is a set of
rules that are shared by a particular service. These rules
determine in which format and with which command set
your application can access the service, as well as what
data this service can return in the response. The API acts
as a layer between your application and external service.
You do not need to know the internal structure and
features of the service, you just send a certain simple
command and receive data in a predetermined format.
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 (user="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. Here I have
used password as: passwd="yadav"
Host Name – is the server name or Ip address on which MySQL is running. if
you are running on localhost, then you can use host="localhost", or it’s IP, i.e.
127.0.0.0
Database Name – Database name to which you want to connect. Here we are
using Database named database="xii_b" because we have already created this
for our example.
After successful execution of above statements in python following out will be displayed
<mysql.connector.connection.MySQLConnection object at 0x022624F0>
Otherwise an error message will be shown
Output:
Can we change the order of the arguments in connect()
functions? Justify your answer?
Can we change the order of the arguments in connect()
functions? Justify your answer?
Ans.:
Yes. These are called named arguments. To reduce the necessity to know the
order of arguments in a function, Python allows named arguments. When you
call a function, you can precede some or all of the arguments by a name and an
equal sign, to let the function know exactly which argument you are passing to
the function. So if we invoke the connect() function by changing the order of
arguments.
Output:
Output: Statement-2
Understand the Python MySQL Database connection program
import mysql.connector
This line imports the MySQL Connector Python module in your program so you can
use this module’s API to connect MySQL.
from mysql.connector import Error
mysql connector Error object is used to show us an error when we failed to connect
Databases or if any other database error occurred while working with the database.
Example ACCESS DENIED ERROR when username
or password is wrong.
mysql.connector.connect()
Using this method we can connect the MySQL Database, this method accepts four
required parameters: Host, Database, User and Password that we already discussed.
connect() method established a connection to the MySQL database from Python
application and returned a MySQLConnection object. Then we can use
MySQLConnection object to perform various operations on the MySQL Database.
The Connect() method can throw an exception, i.e. Database error if one of the required
parameters is wrong. For example, if you provide a database name that is not present in
MySQL, then Python application throws an exception. So check the arguments that you are
passing to this method.
connection.is_connected()
is_connected() is the method of the MySQLConnection class through which we can verify is
our python application connected to MySQL.
connection.cursor()
This method returns a cursor object. Using a cursor object, we can execute SQL queries. The
MySQLCursor class instantiates objects that can execute operations such as SQL statements.
Cursor objects interact with the MySQL server using a MySQLConnection object.
cursor.close()
Using the cursor’s close method we can close the cursor object. Once we close the cursor
object, we can not execute any SQL statement.
connection.close()
At last, we are closing the MySQL database connection using a close() method of
MySQLConnection class.
Now you know how to connect to MySQL server from python let’s proceed with
creating a table from Python.
Creating Database TRAVEL, Using Database TRAVEL, Creating Table PASSENGERS
and inserting records into Table PASSENGERS.
mysql> CREATE database TRAVEL;
mysql> USE TRAVEL;
mysql> CREATE TABLE PASSENGERS (TNO CHAR(3), NAME VARCHAR(20), START VARCHAR(10),
END VARCHAR(10));
mysql> INSERT INTO PASSENGERS VALUES ('T1', 'RAVI KUMAR', 'DELHI', 'MUMBAI' );
mysql> INSERT INTO PASSENGERS VALUES ('T2', 'NISHANT JAIN', 'DELHI', 'KOLKATA' );
mysql> INSERT INTO PASSENGERS VALUES ('T3', 'DEEPAK PRAKASH', 'MUMBAI', 'PUNE' );
mysql> SELECT * FROM PASSENGERS;
+--------+-------------------------+--------------+--------------+
| TNO | NAME | START | END |
+--------+-------------------------+--------------+--------------+
| T1 | RAVI KUMAR | DELHI | MUMBAI |
| T2 | NISHANT JAIN | DELHI | KOLKATA |
| T3 | DEEPAK PRAKASH | MUMBAI | PUNE |
+--------+-------------------------+--------------+--------------+
For the following SQL Table named PASSENGERS in a
database TRAVEL:
Output: # Statement 3
If for loop is as follows:
for R in Recs:
print(R)
Cursor object :
The MySQLCursor class instantiates objects that can execute operations such as SQL statements. Cursor objects
interact with the MySQL server using a MySQLConnection object.
How to create cursor object and use it:
We are creating a database named Books if it is already not created with the help of cursor object. Next line
executes the SQL query show databases and store result in MyCursor as collection, whose values are being
fetched in x variable one by one. On execution of above program Books database is created and a list of available
databases is shown.
Output:
Please do the programs given in this power point
presentation and check Python-MySQL connectivity
on your laptop or computer.
We are creating a database named Books if it is already not created with the help of cursor object. Next line
executes the SQL query show databases and store result in MyCursor as collection, whose values are being
fetched in x variable one by one. On execution of above program Books database is created and a list of available
databases is shown.
Output:
How to create table at run time
Table creation is very easy ,if we are already well versed in SQL table creation then we have to
just pass the create table query in execute() method of cursor object. But before table creation
we must open the database. Here we are opening database school(through connect() method)
before student table creation.
Output:
Check the table created in MySQL by the program:
How to change table structure/(add, edit, remove column of a table) at run time
To modify the structure of the table we just have to use alter table query. Below program will add
a column mark in the student table
Python code output and MySQL output:
Output:
How to fetch all records of a table at run time
Output:
Output:
MySQLCursor.fetchall() Method
MyCursor.fetchall()
The method fetches all (or all remaining) rows of a query result set and
returns a list of tuples. If no more rows are available, it returns an empty list.
MySQLCursor.fetchone() Method
This method retrieves the next row of a query result set and returns a single
sequence, or None if no more rows are available. By default, the returned
tuple consists of data returned by the MySQL server, converted to Python
objects.
MySQLCursor.fetchmany() Method
rows = cursor.fetchmany(size=1)
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.
How to fetch one record of a table at run time
We can use such cursor as iterator. There is no point in using buffered cursor
for single fetching of rows. If we don’t use buffered cursor then we will get -1
as output from rowcount.
The reason is that without a buffered cursor, the results are "lazily" loaded,
meaning that "fetchone" actually only fetches one row from the full result set
of the query. When you will use the same cursor again, it will complain that
you still have n-1 results (where n is the result set amount) waiting to be
fetched. However, when you use a buffered cursor the connector fetches ALL
rows behind the scenes and you just take one from the connector so the mysql
db won't complain.
Output:
How to update record of a table at run time
How to update record of a table at run time
Output:
Before updating marks of rollno 20