Using Transactions in Python Programs

15.7.1 Problem

You want to perform a transaction in a DB-API script.

15.7.2 Solution

Use the standard DB-API transaction support mechanism.

15.7.3 Discussion

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:

 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 ( )

Using the mysql Client Program

Writing MySQL-Based Programs

Record Selection Techniques

Working with Strings

Working with Dates and Times

Sorting Query Results

Generating Summaries

Modifying Tables with ALTER TABLE

Obtaining and Using Metadata

Importing and Exporting Data

Generating and Using Sequences

Using Multiple Tables

Statistical Techniques

Handling Duplicates

Performing Transactions

Introduction to MySQL on the Web

Incorporating Query Resultsinto Web Pages

Processing Web Input with MySQL

Using MySQL-Based Web Session Management

Appendix A. Obtaining MySQL Software

Appendix B. JSP and Tomcat Primer

Appendix C. References

MySQL Cookbook
MySQL Cookbook
ISBN: 059652708X
EAN: 2147483647
Year: 2005
Pages: 412
Authors: Paul DuBois © 2008-2020.
If you may any questions please contact us: