- 事务处理步骤:
- 获取数据库连接。
- 开启事务(通常通过设置自动提交为
false
)。
- 执行多个数据库操作(SQL语句)。
- 如果所有操作都成功,提交事务。
- 如果有任何操作失败,回滚事务。
- 关闭数据库连接。
- 关键代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JdbcTransactionExample {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement insertStmt = null;
PreparedStatement updateStmt = null;
try {
// 1. 获取数据库连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdatabase", "username", "password");
// 2. 开启事务
connection.setAutoCommit(false);
// 插入数据到users表
String insertSql = "INSERT INTO users (username, email) VALUES (?,?)";
insertStmt = connection.prepareStatement(insertSql);
insertStmt.setString(1, "testUser");
insertStmt.setString(2, "test@example.com");
insertStmt.executeUpdate();
// 更新orders表
String updateSql = "UPDATE orders SET status =? WHERE order_id =?";
updateStmt = connection.prepareStatement(updateSql);
updateStmt.setString(1, "processed");
updateStmt.setInt(2, 1);
updateStmt.executeUpdate();
// 3. 如果所有操作都成功,提交事务
connection.commit();
System.out.println("事务提交成功");
} catch (SQLException e) {
// 4. 如果有任何操作失败,回滚事务
if (connection != null) {
try {
connection.rollback();
System.out.println("事务回滚");
} catch (SQLException ex) {
ex.printStackTrace();
}
}
e.printStackTrace();
} finally {
// 5. 关闭数据库连接
if (insertStmt != null) {
try {
insertStmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (updateStmt != null) {
try {
updateStmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}