JDBC Transaction Control Guide

In JDBC, transaction control can be achieved through the following steps:

  1. Getting a database connection: First, obtain a database connection using DriverManager.
  2. Disable automatic submission: After establishing the connection, set automatic submission to false, so that you can manually control the submission and rollback of transactions.
  3. To start a transaction, begin by calling the setAutoCommit(false) method on the Connection object.
  4. Execute SQL commands: Following the start of a transaction, you can use either a Statement or PreparedStatement object to execute SQL commands, such as insert, update, and delete operations.
  5. Submit Transaction: If all operations are successfully executed, the transaction can be committed by calling the commit() method of the Connection object.
  6. Roll back transaction: If an error occurs during execution or if the transaction needs to be rolled back, you can do so by calling the rollback() method of the Connection object.
  7. Close the connection: Lastly, remember to close the connection and release resources.

Here is a simple example code:

Connection conn = null;
Statement stmt = null;

try {
    conn = DriverManager.getConnection(url, username, password);
    conn.setAutoCommit(false);

    stmt = conn.createStatement();
    stmt.executeUpdate("INSERT INTO table_name(column1, column2) VALUES(value1, value2)");

    conn.commit();
} catch (SQLException e) {
    if (conn != null) {
        try {
            conn.rollback();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    e.printStackTrace();
} finally {
    if (stmt != null) {
        stmt.close();
    }
    if (conn != null) {
        conn.setAutoCommit(true);
        conn.close();
    }
}

In the example above, we first establish a database connection and disable autocommit, then we begin a transaction, execute SQL statements within the transaction, rollback the transaction if an exception occurs, and finally close the connection. This achieves simple transaction control.

bannerAds