JDBC Transaction Control Guide
In JDBC, transaction control can be achieved through the following steps:
- Getting a database connection: First, obtain a database connection using DriverManager.
- Disable automatic submission: After establishing the connection, set automatic submission to false, so that you can manually control the submission and rollback of transactions.
- To start a transaction, begin by calling the setAutoCommit(false) method on the Connection object.
- 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.
- Submit Transaction: If all operations are successfully executed, the transaction can be committed by calling the commit() method of the Connection object.
- 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.
- 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.