Problem Solution Discussion Using Transactions in Java Programs

mysql_query COMMIT, conn_id ; }

15.7 Using Transactions in Python Programs

15.7.1 Problem

You want t o perform a t ransact ion in a DB- API script .

15.7.2 Solution

Use t he st andard DB- API t ransact ion support m echanism .

15.7.3 Discussion

The Pyt hon DB- API abst ract ion provides t ransact ion processing cont rol t hrough connect ion obj ect m et hods. I nvoke begin t o begin a t ransact ion and eit her commit or rollback t o end it . The begin and commit calls go int o a try block, and t he rollback goes int o t he corresponding except block t o cancel t he t ransact ion 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

15.8 Using Transactions in Java Programs

15.8.1 Problem

You want t o perform a t ransact ion in a JDBC script .

15.8.2 Solution

Use t he st andard JDBC t ransact ion support m echanism .

15.8.3 Discussion

To perform t ransact ions in Java, use your Connection obj ect t o t urn off aut o- com m it m ode. Then, aft er issuing your queries, use t he obj ect s commit m et hod t o com m it t he t ransact ion or rollback t o cancel it . Typically, you execut e t he st at em ent s for t he t ransact ion in a try block, w it h commit at t he end of t he block. To handle failures, invoke rollback in t he corresponding except ion handler: try { conn.setAutoCommit false; Statement s = conn.createStatement ; move some money from one person to the other s.executeUpdate UPDATE money SET amt = amt - 6 WHERE name = Eve; s.executeUpdate UPDATE money SET amt = amt + 6 WHERE name = Ida; s.close ; conn.commit ; conn.setAutoCommit true; } catch SQLException e { System.err.println Transaction failed, rolling back.; Cookbook.printErrorMessage e; empty exception handler in case rollback fails try { conn.rollback ; conn.setAutoCommit true; } catch Exception e2 { } }

15.9 Using Alternatives to Transactions