事务是数据库操作的基本单位,它确保一组数据库操作要么全部成功,要么全部失败。如果事务中的任何一条SQL语句执行失败,那么整个事务将被回滚到事务开始之前的状态。
MySQL支持以下几种事务隔离级别:
事务通常用于以下场景:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class TransactionExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "username";
String password = "password";
Connection conn = null;
PreparedStatement pstmt1 = null;
PreparedStatement pstmt2 = null;
try {
// 1. 获取数据库连接
conn = DriverManager.getConnection(url, user, password);
// 2. 关闭自动提交,开启事务
conn.setAutoCommit(false);
// 3. 执行第一个SQL语句
String sql1 = "UPDATE accounts SET balance = balance - 100 WHERE id = 1";
pstmt1 = conn.prepareStatement(sql1);
pstmt1.executeUpdate();
// 4. 执行第二个SQL语句
String sql2 = "UPDATE accounts SET balance = balance + 100 WHERE id = 2";
pstmt2 = conn.prepareStatement(sql2);
pstmt2.executeUpdate();
// 5. 提交事务
conn.commit();
System.out.println("Transaction committed successfully.");
} catch (SQLException e) {
// 6. 发生异常,回滚事务
if (conn != null) {
try {
conn.rollback();
System.out.println("Transaction rolled back due to an error: " + e.getMessage());
} catch (SQLException ex) {
ex.printStackTrace();
}
}
} finally {
// 7. 关闭资源
try {
if (pstmt1 != null) pstmt1.close();
if (pstmt2 != null) pstmt2.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
rollback
方法。catch
块中调用conn.rollback()
方法,并且捕获所有可能的异常。conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ)
。finally
块中关闭所有资源,或者使用try-with-resources
语句。通过以上步骤和示例代码,您可以实现MySQL事务的回滚,并处理常见的问题。
领取专属 10元无门槛券
手把手带您无忧上云