Python-Module IV
Database Programming
Python allows us to connect to various databases through database interfaces.
Python’s database interface is DB-API(Data Base- Application Programming Interface).
We can choose the database which we want to connect to Python. Python DB-API
supports a large number of databases like Oracle, MS-SQL server 2000, MySQL, mSQL,
Sybase etc. for using each database we need to download separate DB-API modules.
Connecting To a Database
Standard steps for Python database Programming:
1. import database-specific module
2. Establish a Connection towards the database.
3. Create a Cursor object
4. Use In-built methods to execute the SQL queries
5. Commit or rollback
6. Fetch the result from the Cursor
7. Close the resources
Following Python code shows how to connect MYSQL database with Python. If the database does not
exist, then it will be created and finally a database object will be returned.
Example program
import pymysql
db=pymysql.connect(host=“localhost”,user=”user”,passwd=”pass”,”SA
MPLE”)
cursor=db.cursor()
cursor.execute(“SELECT VERSION()”)
data=cursor.fetchone()
print(“Database version :”,data)
db.close()
In the above example, a connection is established with the data source and a connection object is
returned. In our example, the connection object is saved to db. If connection is not properly
established, db will store the value None. The database object db is used to create a cursor object
cursor and this cursor is used for executing SQL queries. At the end database connection is closed
and resources are released.
CREATING TABLES
Once connection is successfully established, we can create the tables. Creation of tables, insertion,
updation and deletion operations are performed in Python with the help of execute() statement.
Example program
import pymysql
db=pymysql.connect(host=“localhost”,user=”user”,passwd=”pass”,”SA
MPLE”)
cursor=db.cursor()
sql=”CREATE TABLE DEPT(
DEPTNO INT,
DEPTNAME CHAR(20),
LOCATION CHAR(25))”
cursor.execute(sql)
db.commit()
db.close()
The program creates a table called DEPT with fields DEPTNO, DEPTNAME and LOCATION. The SQl
statement for creating the table is stored in sql and the sql is passed to execute() method for
creating the table.
INSERT OPERATION
Once table is created, we need to insert values to the table. The values can be inserted using the
INSERT statement of SQL. The following example shows insert operation.
import pymysql
db=pymysql.connect(host=“localhost”,user=”user”,passwd=”pass”,”SA
MPLE”)
cursor=db.cursor()
sql=”INSERT INTO DEPT(DEPTNO,DEPTNAME,LOCATION)
VALUES(101,Sales,’Kannur’)”
cursor.execute(sql)
db.commit()
db.close()
A record with specified values will be inserted into the DEPT table.
UPDATE OPERATION
UPDATE operation is done to modify existing values available in the table. We can update one or more
records at the same time. The following example shows how to update records in a tale from Python.
import pymysql
db=pymysql.connect(host=“localhost”,user=”user”,passwd=”pass”,”SA
MPLE”)
cursor=db.cursor()
sql=”UPDATE DEPT SET LOCATION = ‘Kozhikode’ WHERE
DEPTNAME=’Sales’”
cursor.execute(sql)
db.commit()
db.close()
The above example updates the location of sales department from Kannur to Kozhikode. If there is
more than one record with the satisfied condition, then all those records will be updated.
DELETE OPERATION
DELETE operation is required when we want to delete some undesired or unwanted records from a
table. We can specify DELETE operation with or without conditions. The following example shows how
to delete records from a table.
import pymysql
db=pymysql.connect(host=“localhost”,user=”user”,passwd=”pass”,”SA
MPLE”)
cursor=db.cursor()
sql=”DELETE FROM DEPT WHERE LOCATION = ‘Kochi’
cursor.execute(sql)
db.commit()
db.close()
The above example will delete all records with location Kochi.
READ OPERATION
READ operation is used to fetch desired records from a database. There are several methods for
fetching records from a database. Once a connection is established, we can make queries to a
database. The following methods are used in READ operation.
1. fetchone() : It fetches the next row of query result set. A result set is an object that is
returned when a cursor object is used to query a table.
Example
import pymysql
db=pymysql.connect(host=“localhost”,user=”user”,passwd=”pass”,”SA
MPLE”)cursor=db.cursor()
sql=”SELECT LOCATION FROM DEPT”
cursor.execute(sql)
row=cursor.fetchone()
#Fetches the next record. In this case first record
if row:
print(“Location:”,row[0])
db.close()
output
Location: Kannur
2. fetchall(): It fetches all the rows in a result set. If some
rows has already been extracted from the result set, then it
retrieves the remaining rows from the result set.that is returned
when a cursor object is used to query a table.
Example
import pymysql
db=pymysql.connect(host=“localhost”,user=”user”,passwd=”pass”,”SA
MPLE”)cursor=db.cursor()
sql=”SELECT LOCATION FROM DEPT”
cursor.execute(sql)
rows=cursor.fetchall()
#Fetch all the records
for row in rows:
print(“Location:”,row[0])
db.close()
output
Location:Kannur
Location:Kozhikode
Location:Kochi
TRANSACTION CONTROL
A transaction is a logical unit of work that contains one or more SQL statements. A transaction
is an atomic unit. Transaction is a mechanism to ensure data consistency. Transaction ensures 4
properties generally referred to as ACID properties.
Atomicity: ensures that all operations within the work unit are completed successfully,
otherwise, the transaction is aborted at the point of failure, and previous operations are rolled back
to their former state.
Consistency: ensures that the database properly change states upon a successfully committed
transaction.
Isolation: enable transaction to operate independently and transparent to each other.
Durability: ensures that the result or effect of a committed transaction persistes in case of a
system failure.
COMMIT()
The COMMIT command is the transactional command used to save changes invoked by a transaction
to the database. The COMMIT command saves all transactions to the database since the last COMMIT
or ROLLBACK command.
The syntax for commit statement is
db.commit()
ROLLBACK()
The ROLLBACK command is the transactional command used to undo transactions that have not
already been saved to the database. The ROLLBACK command can only be used to undo transactions
since the last COMMIT or ROLLBACK command was issued. The syntax for rollback is
db.rollback()
Example program for COMMIT and ROLLBACK
import pymysql
db=pymysql.connect(host=“localhost”,user=”user”,passwd=”pass”,”SA
MPLE”)cursor=db.cursor()
sql=”INSERT INTO DEPT(DEPTNO,DEPTNAME,LOCATION)
VALUES(101,Sales,’Kannur’)”
cursor.execute(sql)
#Commit changes in the database
db.commit()
except:
#Rollback in case there is any error
db.rollback()
db.close()