0% found this document useful (0 votes)
21 views

Lecture - 5 - Database Handling in Python - Tagged

learn how to handel database in python

Uploaded by

aziz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Lecture - 5 - Database Handling in Python - Tagged

learn how to handel database in python

Uploaded by

aziz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

SHAQRA UNIVERSITY

College of Computing and Information


Technology

Programming Language (2)


CSC 213
Database Handling in Python
Programming
Introduction
Pre-requisite to connect Python
with MySQL
Before we start, ensure you have the following installed on your system:

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:

<connection-object> = mysql.connector.connect(host = <host-name>,


user = <username>, passwd = <password>, database = <database> )

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.

Example : to establish connection with MySQL


Create a cursor instance
When we connect to a database from within a script/program, then the query gets sent to the
server, where it gets executed, and the resultset (the set of records retrieved as per query) is
sent over the connection to you, in one burst of activity, i.e. in one go.

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:

<cursor-object>.execute(sql query string>)

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.

You would need special privileges to create or to delete a MySQL database.


So if you have access to the root user, you can create any database.

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…..

#Retrieving the list of databases


print("List of databases: ")
cursor.execute("SHOW DATABASES")
print(cursor.fetchall())
#Closing the connection
conn.close()
Example
Following example creates a table named Employee in the database mydb.
import mysql.connector

conn = mysql.connector.connect(user='root', password='password', host='127.0.0.1',


database='mydb’)

cursor = conn.cursor()

cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")

sql =‘’’CREATE TABLE EMPLOYEE(


FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT)'‘’

cursor.execute(sql)

conn.close()
The following example executes SQL INSERT statement to insert a record into the
EMPLOYEE table:

import mysql.connector

conn = mysql.connector.connect(user='root', password='password', host='127.0.0.1’,


database='mydb’)

cursor = conn.cursor()

sql = """INSERT INTO


EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""

try:
cursor.execute(sql)
conn.commit()
except:
conn.rollback()

conn.close()
Following example inserts a record into the Employee table dynamically.
import mysql.connector

conn = mysql.connector.connect(user='root', password='password', host='127.0.0.1',


database='mydb’)

cursor = conn.cursor()

insert_stmt = (“INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME)" "VALUES (%s,
%s, %s, %s, %s)" )

data = ('Ramya', 'Ramapriya', 25, 'F', 5000)

try:
cursor.execute(insert_stmt, data)
conn.commit()
except:
# Rolling back in case of error
conn.rollback()

print("Data inserted")

conn.close()
Thank You 

You might also like