Connecting Python With SQL Database
Connecting Python With SQL Database
Database
OBJECTIVE
To make student
aware about
Connectivity between
frontend -backend
PREREQUISITE
import MySQLdb
MySQLdb
import MySQldb
What is Connection •The next step to using
MySQL in your Python
scripts is to make a
connection to the
database that you wish
to use. All Python DB-
API modules implement
a function
'module_name.connect‘
Db=MySQLdb.connect
(“localhost”, testuser”,
”test123”, ”TESTDB”)
Connecting to a MySQL database
:
host
Your Local Your
Name of the Password
Database
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
Create Cursor
cur=db.cursor()
•The next step is to create a
What is Cursor Cursor object.
•It will let you execute all the
queries you need
•In order to put our new
connnection to good use we
need to create a cursor
object.
•The cursor object is an
abstraction specified in the
Python DB-API
•It gives us the ability to
have multiple seperate
working environments
through the same
connection to the database.
•We can create a cursor by
executing the 'cursor'
function of your database
Example of Simple Code to Connect MySQL with Python
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
cursor = db.cursor()
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
Delete information into databse table
➢DELETE operation is required when you want to delete some records from your
database. Following is the procedure to delete all the records from EMPLOYEE where
AGE is more than 20
➢Example
import MySQLdb
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
cursor = db.cursor()
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
Disconnecting Database
db.close()
Thank You