Lecture - 5 - Database Handling in Python - Tagged
Lecture - 5 - Database Handling in Python - Tagged
1. Python 3: You can download and install Python from the official website
(https://www.python.org/). Make sure to install the latest version of Python.
2. MySQL: You can download and install MySQL from the official website
(https://www.mysql.com/). You will also need to create a database and set up a
user with the appropriate permissions.
3. mysql-connector-python library: You can install this library using pip, the Python
package manager. Open a terminal and run the following command:
pip install mysql-connector-python
Pre-requisite to connect Python with MySQL
Connecting to MySQL from Python
Import mysql.connector Package
First of all you need to import mysql.connector package in your Python scripts. For
this, write import command as shown below:
import mysql.connector
or
import mysql.connector as ms
Open a connection to database
The connect( ) function of mysql.connector establishes connection to a MySQL
database and requires four parameters, which are:
Import mysql.connector
Mycon = connector.connect(….)
The above command will establish connection to MySQL database with user as “root” ,
password as “MyPass” and to the MySQL database namely test which exists on the MySQL.
You can also check for successful connection using function is_connected( ) with
connected object, which returns True , if connection is successful.
And in order to do the processing of data row by row, a special control structure is used, which
is called Database Cursor.
Syntax:
<cursor-object> = <connection-object>.cursor( )
Example:
Execute a query
Once you have created a cursor, you can execute SQL query using execute( ) function
with cursor object as per following syntax:
Example:
The above code will execute the given SQL query and store the retrieved records
(i.e. , the resultset) in the cursor object (namely cursor) which you can then use in your
program/scripts as required.
The fetchall( ) method
The fetchall() method retrieves all the rows in the result set of a query and
returns them as list of tuples.
(If we execute this after retrieving few rows it returns the remaining ones).
The fetchone( ) method
The fetchone() method fetches the next row in the result of a query and
returns it as a tuple.
Example fetchone( ) method
The fetchmany( ) method
The fetchmany() method is similar to the fetchone() but, it retrieves the next set of
rows in the result set of a query, instead of a single row.
Creating a database in MySQL using python
After establishing connection with MySQL,
to manipulate data in it you need to connect to a database.
You can connect to an existing database or, create your own.
Following example establishes connection with MYSQL and creates a database in it.
import mysql.connector
#establishing the connection
conn = mysql.connector.connect(user='root',password='password', host='127.0.0.1')
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Doping database MYDATABASE if already exists.
cursor.execute("DROP database IF EXISTS MyDatabase")
#Preparing query to create a database
sql = "CREATE database MYDATABASE";
#Creating a database
cursor.execute(sql) Cont…..
Cont…..
cursor = conn.cursor()
cursor.execute(sql)
conn.close()
The following example executes SQL INSERT statement to insert a record into the
EMPLOYEE table:
import mysql.connector
cursor = conn.cursor()
try:
cursor.execute(sql)
conn.commit()
except:
conn.rollback()
conn.close()
Following example inserts a record into the Employee table dynamically.
import mysql.connector
cursor = conn.cursor()
insert_stmt = (“INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME)" "VALUES (%s,
%s, %s, %s, %s)" )
try:
cursor.execute(insert_stmt, data)
conn.commit()
except:
# Rolling back in case of error
conn.rollback()
print("Data inserted")
conn.close()
Thank You