0% found this document useful (0 votes)
29 views67 pages

DB Connectivity

Rt

Uploaded by

38sandeep gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views67 pages

DB Connectivity

Rt

Uploaded by

38sandeep gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 67

Database

Connectivity
in Python:
What is MySQLdb?

• MySQLdb is an interface for connecting to a


MySQL database server from Python.
Installing MySQL connector

• You can choose the right database for your


application.
• Python Database API supports a wide range of
database servers such as –GadFly, mSQL,
MySQL, PostgreSQL, Microsoft SQL Server
2000,Informix,Interbase,Oracle,Sybase.
• You must download a separate DB API module
for each database you need to access.
• For example, if you need to access an Oracle
database as well as a MySQL database, you
must download both the Oracle and the MySQL
database modules.
• The DB API provides a minimal standard for
working with databases using Python structures
and syntax wherever possible. This API includes
the following:

1.Importing the API module.


2.Acquiring a connection with the database.
3.Issuing SQL statements.
4.Closing the connection
Installing mysql connector

• Before proceeding, you make sure you have


MySQLdb installed on your machine. Just type
the following in your Python script and execute
it:
import MySQLdb

If it produces the following result, then it means


MySQLdb module is not installed:
Traceback (most recent call last): File "test.py", line 3, in <module>
import MySQLdb ImportError: No module named 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.

• The Python database modules connect to the


database.

• Each database module needs to provide a


connect function that returns a connection
object.
The following table lists the
most common parameters.
Parameter Usage

Host Host or network system


name on which the
database runs
Database Name of the database
User User name for
connecting to the
database
Password Password for the given
user name
Example
import MySQLdb
# Open database connection
db =
MySQLdb.connect("localhost",“user",“password","TESTDB
")
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print "Database version : %s " % data
# disconnect from server
db.close()
output
Working with Cursors

•A cursor is a Python object that enables you to


work with the database.
•In database terms, the cursor is positioned at a
particular location within a table or tables in the
database.
• To get a cursor, you need to call the cursor
method on the connection object:
•cursor = conn.cursor()
• Once you have a cursor, you can perform
operations on the database, such as inserting
• import MySQLdb
# Open database connection
db = MySQLdb.connect("127.0.0.1","root","patkar","test")

# prepare a cursor object using cursor() method


cursor = db.cursor()

# execute SQL query using execute() method.


cursor.execute("SELECT VERSION()")

# Fetch a single row using fetchone() method.


data = cursor.fetchone()
INSERT Operation

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

• READ Operation on any database means to fetch


some useful information from the database.
• Once our database connection is established, you
are ready to make a query into this database.
• You can use either fetchone() method to fetch
single record or fetchall() method to fetch
multiple values from a database table.
• fetchone(): It fetches the next row of a query
result set. A result set is an object that is returned
when a cursor object is used to query a table.
• fetchall(): It fetches all the rows in a result set. If
some rows have already been extracted from the
result set, then it retrieves the remaining rows
from the result set.
• rowcount: This is a read-only attribute and
returns the number of rows that were affected by
an execute() method.
Example

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

fname=Mac, lname=Mohan, age=20,


income=2000
Update Operation

• 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 gender as 'M'. Here, we
increase AGE of all the males by one year.
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 UPDATE required


records

sql = "UPDATE EMPLOYEE SET AGE = AGE + 1


WHERE sex= '%c'" % ('M')
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
DELETE Operation

• 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
# 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

• Transactions are a mechanism that ensures


data consistency. Transactions have the
following four properties:
• Atomicity: Either a transaction completes or
nothing happens at all.
• Consistency: A transaction must start in a
consistent state and leave the system in a
consistent state.
• Isolation: Intermediate results of a
transaction are not visible outside the current
transaction.
• Durability: Once a transaction was
committed, the effects are persistent, even
after a system failure.
Example

• You already know how to implement


transactions. Here is again similar example −
# 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()
COMMIT Operation

• Commit is the operation, which gives a green


signal to database to finalize the changes, and
after this operation, no change can be
reverted back.
• Here is a simple example to call commit
method.
• db.commit()
ROLLBACK Operation

• If you are not satisfied with one or more of the


changes and you want to revert back those
changes completely, then use rollback()
method.
• Here is a simple example to call rollback()
method.
• db.rollback()
Disconnecting Database

• To disconnect Database connection, use close()


method.
• db.close()
• If the connection to a database is closed by the
user with the close() method, any outstanding
transactions are rolled back by the DB.
• However, instead of depending on any of DB
lower level implementation details, your
application would be better off calling commit
or rollback explicitly.
Handling Errors

• There are many sources of errors.


• A few examples are a syntax error in an
executed SQL statement, a connection failure,
or calling the fetch method for an already
canceled or finished statement handle.
• The DB API defines a number of errors that
must exist in each database module. The
following table lists these exceptions.
Exception Description

Error Base class for errors. Must subclass StandardError.

InterfaceErr Used for errors in the database module, not the


or database itself.

DatabaseEr
Used for errors in the database. Must subclass Error.
ror

Subclass of DatabaseError that refers to errors in the


DataError
data.

Subclass of DatabaseError that refers to errors such as


Operational the loss of a connection to the database. These errors
Error are generally outside of the control of the Python
scripter.
Exception Description

Subclass of DatabaseError for situations that would


IntegrityErr
damage the relational integrity, such as uniqueness
or
constraints or foreign keys.

Subclass of DatabaseError that refers to errors


InternalErr
internal to the database module, such as a cursor no
or
longer being active.
Subclass of DatabaseError that refers to errors such
Programmi
as a bad table name and other things that can safely
ngError
be blamed on you.

NotSupport Subclass of DatabaseError that refers to trying to call


edError unsupported functionality.
• Your Python scripts should handle these errors,
but before using any of the above exceptions,
make sure your MySQLdb has support for that
exception.
• import MySQLdb as my

• try:

• db = my.connect(host="127.0.0.1",
• user="root",
• passwd="patkar",
• db="testdb"
• )
• cursor = db.cursor()

• sql = "select * from employee"


• number_of_rows = cursor.execute(sql)
• print(number_of_rows)
• db.close()
• except my.DataError as e:
• print("DataError")
• print(e)
• except my.InternalError as e:
• print("InternalError")
• print(e)
• except my.IntegrityError as e:
• print("IntegrityError")
• print(e)
• except my.OperationalError as e:
• print("OperationalError")
• print(e)
• except my.NotSupportedError as e:
• print("NotSupportedError")
• print(e)
• except my.ProgrammingError as e:
• print("ProgrammingError")
• print(e)
• except :
• print("Unknown error occurred")

You might also like