Show List

Working with Transactions

In JDBC, transactions allow multiple statements to be executed as a single unit of work, either all the statements are executed or none of them. Transactions are typically used to ensure data consistency and integrity.

Here's an example of how to work with transactions in JDBC:

Connection conn = null;
try {
   conn = DriverManager.getConnection(DB_URL, USER, PASS);
   conn.setAutoCommit(false); // disable auto-commit
   Statement stmt = conn.createStatement();
   stmt.executeUpdate("INSERT INTO accounts (name, balance) VALUES ('John Doe', 1000)");
   stmt.executeUpdate("INSERT INTO accounts (name, balance) VALUES ('Jane Doe', 500)");
   conn.commit(); // commit the transaction
} catch (SQLException e) {
   if (conn != null) {
      try {
         conn.rollback(); // roll back the transaction in case of error
      } catch (SQLException ex) {
         ex.printStackTrace();
      }
   }
   e.printStackTrace();
} finally {
   if (conn != null) {
      try {
         conn.setAutoCommit(true); // enable auto-commit
         conn.close();
      } catch (SQLException e) {
         e.printStackTrace();
      }
   }
}
In this example, the connection's auto-commit mode is first set to false, so that multiple statements can be executed as a single transaction. The two INSERT statements are executed, and the transaction is committed by calling the conn.commit() method. In case of any error, the conn.rollback() method is called to roll back the transaction and the database is left unchanged. Finally, the auto-commit mode is set back to true and the connection is closed.

    Leave a Comment


  • captcha text