Skip to Content
MySQL Cookbook, 2nd Edition
book

MySQL Cookbook, 2nd Edition

by Paul DuBois
November 2006
Intermediate to advanced
977 pages
30h 42m
English
O'Reilly Media, Inc.
Content preview from MySQL Cookbook, 2nd Edition

Using Transactions in Python Programs

Problem

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

Solution

Use the standard DB-API transaction support mechanism.

Discussion

The Python DB-API abstraction provides transaction processing control through connection object methods. The DB-API specification indicates that database connections should begin with auto-commit mode disabled. Therefore, when you open a connection to the database server, MySQLdb disables auto-commit mode, which implicitly begins a transaction. End each transaction with either commit() or rollback(). The commit() call occurs within a try statement, and the rollback() occurs within the except clause to cancel the transaction if an error occurs:

try:
  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
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

MySQL Cookbook, 3rd Edition

MySQL Cookbook, 3rd Edition

Paul DuBois
MySQL 8 Cookbook

MySQL 8 Cookbook

Karthik Appigatla
MySQL Cookbook

MySQL Cookbook

Paul DuBois
MySQL Cookbook, 4th Edition

MySQL Cookbook, 4th Edition

Sveta Smirnova, Alkin Tezuysal

Publisher Resources

ISBN: 059652708XSupplemental ContentErrata Page