October 2002
Intermediate to advanced
1024 pages
27h 26m
English
You want to perform a transaction in a DB-API script.
Use the standard DB-API transaction support mechanism.
The Python DB-API abstraction provides transaction processing control
through connection object methods. Invoke begin( )
to begin a transaction and either commit( ) or
rollback( ) to end it. The begin( ) and commit( ) calls go into a
try block, and the rollback( )
goes into the corresponding except block to cancel
the transaction if an error occurs:
try:
conn.begin ( )
cursor = conn.cursor ( )
# move some money from one person to the other
cursor.execute ("UPDATE money SET amt = amt - 6 WHERE name = 'Eve'")
cursor.execute ("UPDATE money SET amt = amt + 6 WHERE name = 'Ida'")
cursor.close ( )
conn.commit( )
except MySQLdb.Error, e:
print "Transaction failed, rolling back. Error was:"
print e.args
try: # empty exception handler in case rollback fails
conn.rollback ( )
except:
pass