Copy of Python Database Connectivity
Copy of Python Database Connectivity
To make student
aware about
Connectivity between
frontend -backend
PREREQUISITE
➢Detailed knowledge of
Python. ➢MySQL
Point to be Focussed
(3 Important Steps)
➢ Download Python 3.5.3 and then install
i➢ Download MySQL API, exe file will be
downloaded install it.
➢ Install MySQL-Python Connector
➢ Now connect MySQL Server using
Python.
What is MySQLdb
What is Connection
What is a Cursor
What is MySQLdb
for connecting to a
MySQL database server
from Python.
• It implements the
Python Database API
and is built on top of
the MySQL C API.
'module_name.connect‘
Connection MySQLdb
Db=MySQLdb.connect
(“localhost”, testuser”,
”test123”, ”TESTDB”)
Connecting to a MySQL
database :
db = MySQLdb.connect(host=MY_HOST,
user=MY_USER, passwd=MY_PASS, db=MY_DB)
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
Create Cursor cur=db.cursor()
What is Cursor
• The next step is to
create a 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 our database
Example of Simple Code to Connect MySQL with Python
➢UPDATE Operation on any database means to update one or more records, which
are already available in the database.
➢The following procedure updates all the records having SEX as 'M'. Here, we
increase AGE of all the males by one year.
➢Example
import MySQLdb
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()
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()
db.commit()
except:
db.rollback()
Disconnecting Database
➢To disconnect Database connection,
use close() method.
db.close()
Thank
You