JDBC Transaction Rollback Tutorial
To roll back a transaction in JDBC, you can use the rollback() method of the Connection object. The specific steps are as follows:
- Firstly, make sure to set the auto commit to false when creating the Connection object, like connection.setAutoCommit(false).
- Before executing the SQL statement, it is necessary to start a transaction, which can be done by using connection.setAutoCommit(false) to disable auto-commit.
- When an exception occurs or a transaction needs to be rolled back, call the connection.rollback() method to rollback.
- You can call the connection.commit() method if you need to manually submit the transaction.
- Lastly, remember to call connection.setAutoCommit(true) to set auto-commit back to true before closing the Connection object.
Here is an example code:
// 创建Connection对象
Connection connection = DriverManager.getConnection(url, username, password);
// 关闭自动提交
connection.setAutoCommit(false);
// 开启事务
try {
// 执行SQL语句
// 如果出现异常,可以调用connection.rollback()进行回滚
// connection.rollback();
// 提交事务
connection.commit();
} catch (SQLException e) {
// 出现异常时回滚事务
connection.rollback();
e.printStackTrace();
} finally {
// 关闭Connection对象时,将自动提交设置回true
connection.setAutoCommit(true);
connection.close();
}