Python MySQL Connectivity
Python MySQL Connectivity
Learning Objectives
http://www.mysql.com/downloads OR dev.mysql.com/download
Type the name of the site
Connotation of Database Connectivity
❖ Every application require data to be stored for future reference.
Today every application stores data in database for this purpose.
❖In school student details are saved for many reasons like attendance, fee
collections, report cards etc.
❖In this session we will consider Python as the Front end and MySQL as the
Backend learn to setup connection between two.
Connecting MySQL with Python
Python has different APIs available for working with different types of
databases, we need to first download the MYSQL API available for Python
These APIs facilitate Python to work with databases in the Python shell as
follows :
Execute a query
Note:- You can execute any SQL query with the help execute() method.
Clean up the Environment
Once the processing on MySQL database is over the connection
as well as cursor is closed by using close() method of the
corresponding object.
➢ Close the MySQL database connection using
<Connectionobject>.close()
For Example :
ob.close()
➢ Close the cursor object using a <cursor object> .close()
For Example :
cur.close()
Simple code to connect MySQL and Python
import mysql.connector as sql
db=sql.connect(host="localhost",user="root",passwd="1234",)
if db.is_connected():
print("successfully connected")
else:
print(“Not connected")
Mycur=db.cursor()
Mycur.execute("create database Employee")
print("successfully created the Database")
Mycur.close()
db.close()
Performing MYSQL Queries
Instead of passing value we will first accept value from the user and the value is
passed to the query using Two Methods
1. OLD STYLE ( Templates with % format)
General form: f%v
f – template string
v – value / values to be formatted( v must be a tuple)