DB Connectivity
DB Connectivity
Connectivity
in Python:
What is MySQLdb?
To install MySQLdb
https://pypi.python.org/pypi/MySQL-python/1.2.5
https://sourceforge.net/projects/mysql-python/files/latest/download
https://www.python.org/downloads/
• Link to install MySQL https://mysql-
com.en.softonic.com/download#downloading
Accessing connector module
• Database Connection
• Before connecting to a MySQL database, make
sure of the followings −
• You have created a database TESTDB.
• You have created a table EMPLOYEE in TESTDB.
• This table has fields FIRST_NAME, LAST_NAME,
AGE and INCOME.
• User ID "testuser" and password "test123" are
set to access TESTDB.
• Python module MySQLdb is installed properly
on your machine.
Creating Connections
• A Connection object provides the means to
communicate from your script to a database
program.
import MySQLdb
# Open database connection
db =
MySQLdb.connect("localhost","testuser","test1
23","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, GENDER, INCOME) VALUES
('Mac', 'Mohan', 20, 'M', 2000)"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
Above example can be written
as follows to create SQL queries
dynamically
import MySQLdb
# Open database connection
db =
MySQLdb.connect("localhost","testuser","test12
3","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the
database
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
LAST_NAME, AGE, GENDER, INCOME) \
VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
('Mac', 'Mohan', 20, 'M', 2000)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
Following code segment is another form
of execution where you can pass
parameters directly
user_id = "test123"
password = "password"
con.execute('insert into Login values("%s",
"%s")' % \
(user_id, password))
Using connect
import MySQLdb
# Open database connection
db =
MySQLdb.connect("localhost","testuser","test12
3","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Drop table if it already exist using execute()
method.
cursor.execute("DROP TABLE IF EXISTS
EMPLOYEE")
# Create table as per requirement
sql = """CREATE TABLE EMPLOYEE ( FIRST_NAME
CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE
INT, GENDER CHAR(1), INCOME FLOAT )"""
cursor.execute(sql)
# disconnect from server
db.close()
READ Operation
import MySQLdb
# Open database connection db =
MySQLdb.connect("localhost","testuser","test12
3","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the
database.
sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > '%d'" % (1000)
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
income = row[3]
# Now print fetched result print "fname=
%s,lname=%s,age=%d,income=%d" % \
(fname, lname, age,income )
except:
print "Error: unable to fetch data“
# disconnect from server
db.close()
output
cursor = db.cursor()
cursor.execute(sql)
db.commit()
db.rollback()
db.close()
output
DELETE Operation
import MySQLdb
# Open database connection
db =
MySQLdb.connect("localhost","testuser","test12
3","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to DELETE required records
sql = "DELETE FROM EMPLOYEE WHERE AGE >
'%d'" % (20)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
output
Executing transactions
DatabaseEr
Used for errors in the database. Must subclass Error.
ror
• try:
• db = my.connect(host="127.0.0.1",
• user="root",
• passwd="patkar",
• db="testdb"
• )
• cursor = db.cursor()