You are on page 1of 34

Python Database Programming

PART 1
Python Database Programming

● Python allows us to connect to various databases through database interfaces.

● Python’s database interface is DB-API (DataBase–Application Programming

Interface).

● We can choose the database which we want to connect to Python.

● Python DB-API supports a large number of databases like Oracle, MS-SQL

server 2000, MySQL, mSQL, Sybase etc.

● For using each database we need to download separate DB-API modules.


Python Database Programming
In Python, We can use the following modules to communicate with MySQL.

● MySQL Connector Python


● PyMySQL
● MySQLDB
● MySqlClient
● OurSQL
Python Database Programming
● Above all interfaces or modules are adhere to Python Database API Specification
v2.0 (PEP 249) that means the syntax, method, and way of access the database
is the same in all.
● PEP 249 is 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 Database Programming
● 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.

How to connect MySQL database in Python

● Let’s see how to connect the MySQL database in Python using the ‘MySQL Connector
Python’ module.
How to Connect to MySQL Database in Python

1. Install MySQL connector module


Use the pip command to install MySQL connector Python.
pip install mysql-connector-python

2. Import MySQL connector module


Import using a import mysql.connector statement so you can use this module’s
methods to communicate with the MySQL database.
How to Connect to MySQL Database in Python

3. Use the connect() method


Use the connect() method of the MySQL Connector class with the required
arguments to connect MySQL. It would return a MySQLConnection object if the
connection established successfully
4. Use the cursor() method
Use the cursor() method of a MySQLConnection object to create a cursor object to
perform various SQL operations.
5. Use the execute() method
The execute() methods run the SQL query and return the result.
How to Connect to MySQL Database in Python

6. Extract result using fetchall()


Use cursor.fetchall() or fetchone() or fetchmany() to read query result.
7. Close cursor and connection objects
use cursor.close() and connection.close() method to close open connections after your
work completes
How to Connect to MySQL Database in Python

● The is_connected() is the method of the MySQLConnection class through


which we can verify is our Python application connected to MySQL.

● At last, we are closing the MySQL database connection using a close()


method of MySQLConnection class.
How to Connect to MySQL Database in Python

● Catch exceptions that may occur during this process by importing the Error
class from the MySQL connector module using a from mysql.connector import
Error statement.
● Error class is useful to debug when we failed to connect to MySQL.
● For example, ACCESS DENIED ERROR when the username or password is
wrong.
● The connect() method can throw a Database error exception if one of the required
parameters is wrong. For example, if you provide a database name that is not
present in MySQL.
Create Tables
Python Insert Into MySQL Table
Python Insert Into MySQL Table

1. Connect to MySQL from Python


Refer to Python MySQL database connection to connect to MySQL database from
Python using MySQL Connector module

2. Define a SQL Insert query


Next, prepare a SQL INSERT query to insert a row into a table. in the insert query,
we mention column names and their values to insert in a table.
For example,

INSERT INTO mysql_table (column1, column2, …) VALUES (value1, value2, …);


Python Insert Into MySQL Table

5. Get Cursor Object from Connection


Next, use a connection.cursor() method to create a cursor object. This method creates
a new MySQLCursor object.

6. Execute the insert query using execute() method


Execute the insert query using the cursor.execute() method. This method executes the
operation stored in the Insert query.

7. Commit your changes


After the successful execution of a query make changes persistent into a database
using the commit() of a connection class.
Python Insert Into MySQL Table

8. Get the number of rows affected


After a successful insert operation, use a cursor.rowcount method to get the number of
rows affected. The count depends on how many rows you are Inserting.

9. Verify result using the SQL SELECT query


Execute a MySQL select query from Python to see the new changes.

10 . Close the cursor object and database connection object


use cursor.close() and connection.close() method to close open connections after your
work completes.
Use Python Variables in a MySQL Insert Query

Sometimes you need to insert a Python variable value into a table’s column.

For example, in the user signup form user enter his/her details.

We can take those values in Python variables and insert them into a table.

● We can insert Python variables into the table using the prepared statement and
parameterized query.
● Using a parameterized query, we can pass Python variables as a query
parameter in which placeholders (%s) used for parameters.
Insert multiple rows into MySQL table using the cursor’s executemany()

Use the cursor’s executemany() function to insert multiple records into a table.

Syntax of the executemany() method.

cursor.executemany(operation, seq_of_params)

This method executes Insert operation against all parameter sequences in the sequence
seq_of_params argument.
Insert multiple rows into MySQL table using the cursor’s executemany()

We need to include lists of tuples in the seq_of_params argument along with the insert
query.

Each tuple inside the list contains a single row that you want to insert.

So we can add as many rows in the list and pass a list to a cursor.executemany()
function along with the insert query.

Note: Each tuple is enclosed within parentheses and separated by commas.


Python Select from MySQL Table

Use the following methods to fetch data returned by a cursor.execute()

● cursor.fetchall() to fetch all rows


● cursor.fetchone() to fetch a single row
● cursor.fetchmany(SIZE) to fetch limited rows
Use Python variables as parameters in MySQL Select Query

To handle such a requirement, we need to use a parameterized query.

A parameterized query is a query in which placeholders (%s) are used for


parameters and the parameter values supplied at execution time.
Python Select from MySQL Table

Syntax of the cursor’s fetchmany()

rows = cursor.fetchmany(size=row_size)

Cursor’s fetchmany() methods return the number of rows specified by size argument, defaults
value of size argument is one.

For example, if the specified size is 5, then it returns five rows.


fetchone()
Python Fetch MySQL row using the column names

To select records from my MySQL table using a column name, we only need to change the
cursor creation.

Replace the standard cursor creation with the following code,cursor =


connection.cursor(dictionary=True)

It creates a cursor that returns rows as dictionaries so we can access using column name
(here column name is the key of the dictionary)

You might also like