AO Logo
 
  
  
  
Profile
Upgrading Tomcat
JDBC Pool
JDBC Transactions
Restart JVM
Control JVM
Shell Compiling
JVM Logs
AO
AO Industries, Inc.
Application Infrastructure ProviderApplication Infrastructure Provider
Sign UpWhat's NewClient AreaContact UsSite Map
 
your location:   home page ··· client area ··· faqs ··· java virtual machines ··· recommended jdbc transaction
Recommended JDBC Transaction
Article Summary

Title: Recommended JDBC Transaction
Description:The recommended transaction lifecycle for JDBC database access
Key Words:recommended, jdbc, sql, database, transaction, lifecycle
Type:FAQs
Category:Java Virtual Machines
Last Updated:2004-01-08 04:59:52

Recommended JDBC Transaction


I want reliable, efficient, consistent, trouble-free, easily-debugged database transactions. How would you recommend I structure my database access code to accomplish all of these goals?



First, we recommend that you use a Recommended JDBC Pool Manager.
Connection conn=pool.getConnection();
try {
  // Begin the transaction
  conn.setAutoCommit(false);  // Not necessary when using AOConnectionPool
  try {
    // Prepared statements are always used to avoid the possibility
    // of embedded SQL from web forms
    PreparedStatement pstmt=conn.prepareStatement(sql);
    try {
      // Set the parameters
      pstmt.set...(...);
      // Execute the query or update
      ResultSet results=pstmt.executeQuery();
      try {
        while(results.next()) {
          // Use results
        }
      } finally {
        results.close();
      }
    } finally {
      pstmt.close();
    }
  } catch(SQLException err) {
    // Log the exact SQL statement that failed.
    System.err.println("SQLException caused by query: "+pstmt.toString());

    // Close the connection, just in case establishing a new connection will
    // clear up the error
    if(!conn.isClosed()) {
      conn.rollback();
      conn.close();
    }

    // Rethrow the exception because this is just connection cleanup, not
    // error handling
    throw err;
  } finally {
    // Commit any successful transactions and end the transaction
    if(!conn.isClosed()) {
      conn.commit();
      conn.setAutoCommit(true);  // Not necessary when using AOConnectionPool
    }
  }
} finally {
  // The connection is always released to the pool
  pool.releaseConnection(conn);
}
Copyright © 2000-2024 AO Industries, Inc.