Using Transactions in Java Programs

15.8.1 Problem

You want to perform a transaction in a JDBC script.

15.8.2 Solution

Use the standard JDBC transaction support mechanism.

15.8.3 Discussion

To perform transactions in Java, use your Connection object to turn off auto-commit mode. Then, after issuing your queries, use the object's commit( ) method to commit the transaction or rollback( ) to cancel it. Typically, you execute the statements for the transaction in a try block, with commit( ) at the end of the block. To handle failures, invoke rollback( ) in the corresponding exception 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) { }
}

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

Similar book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net