You are on page 1of 9

BCSE-3072

Industry Oriented Python-2


Database connectivity
Transactions, commit and rollback operations

Prepared by:
Ravindra Kumar Chahar
Galgotias University
Transaction Processing
Transaction processing availability allows users
to work on the database concurrently. At the
same time it also ensures that each user sees
a consistent version of data and that all the
changes are applied in the right order. Oracle
uses locks to control concurrent access to data
and locks only the minimal amount of data
necessary for the least possible time.
Using commit
Role of commit:
(i) It marks the end of current transaction
(ii) It helps us to save changes made during that
transaction permanent and is visible to all users.
(iii) Example:
update item set qty = qty – 1
where itemid = ‘STN001’;
commit;
Using Rollback
Role of rollback:
(i) It ends the current transaction
(ii) It helps in undoing any changes made during that
transaction
(iii) Thus making mistakes, such as deleting a wrong row can
be restored with the help of this statement.
(iv) Example:
INSERT INTO item (itemid, itemname) values (‘STN001’, ‘Tool’);
rollback;
The changes made by Insert statement has been undone.
Using Savepoint
Example:

INSERT INTO emp values (1004, 6000);


savepoint s1;
Update emp set sal= 100000
where empno =1002;
savepoint s2;
Delete from emp where empno = 1003;
savepoint s3;
rollback;
This statement would restore all the changes which
were made in emp table.
Instead if we want to retain INSERTION and
UPDATION happened earliar and discarding the
deletion alone then we need to say
rollback to s2.
Now, whatever the savepoint(s) which we have after
S2 will be cleared. Hence, S3 will be cleared.
• The no. of save-points for each session is
unlimited.
• These save-points are alive only for the
current session in which it is created.
Sample Python code
# Database connectivity – using commit and rollback
import sqlite3
conn= sqlite3.connect('ABC1.db')
cur=conn.cursor()
#cur.execute("CREATE TABLE TEST2 (NAME VARCHAR(6), MARKS INT);")
cur.execute("INSERT INTO TEST2 VALUES ('Himani', 98);")
cur.execute("INSERT INTO TEST2 VALUES ('Ramesh',91);")

cur.execute("UPDATE TEST2 SET MARKS= 95 WHERE NAME='Ramesh';")


conn.commit() # The changes made with INSERT and UPDATE ARE STORED
# PERMANENTLY
cur.execute("UPDATE TEST2 SET MARKS= 99 WHERE NAME='Himani';")
conn.rollback() # The changes made using above update are undone
cur.execute("SELECT * FROM TEST2 WHERE MARKS >= :VALUE;",{'VALUE':70})
for row in cur:
print(row)

conn.close()
Output:
('Himani', 98)
('Ramesh', 95)

You might also like