测试的是一个 JDBC 事务中可能包含对多个 JDBC 事务的操作,当该事务中的任何一个方法抛出异常后所有的 JDBC 事务均回滚。本例中 update2 的 preparedStatement2.executeUpdate()却无法执行,为什么?
public class JdbcDemo21 {
public static void main(String[] args) {
try {//加载 MySql 的驱动类
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("找不到驱动程序类 ,加载驱动失败!");
e.printStackTrace();
}
String url = "jdbc:mysql://1.fdsf229.fdsf:307/test";
String dbusername = "root";
String dbpassword = "root";
try {
Connection con = DriverManager.getConnection(url, dbusername, dbpassword);
Connection con2 = DriverManager.getConnection(url, dbusername, dbpassword);
con.setAutoCommit(false);
con2.setAutoCommit(false);
Savepoint conSavepoint = con.setSavepoint();
update1(con);
update2(con2, con, conSavepoint);
con2.commit();
con.commit();
con.close();
con2.close();
} catch (SQLException se) {
System.out.println("数据库连接失败!");
se.printStackTrace();
}
}
private static void update1(Connection con) throws SQLException {
String sql = "update user set count = count - 100 where username = 'zhangsan'";
PreparedStatement preparedStatement = con.prepareStatement(sql);
int i = preparedStatement.executeUpdate();
}
private static void update2(Connection con, Connection connection, Savepoint conSavepoint) throws SQLException {
try {
String sql2 = "update user set count = count + 100 where username = 'lisi'";
PreparedStatement preparedStatement2 = con.prepareStatement(sql2);
int i1 = preparedStatement2.executeUpdate();
int errorTemp = 1 / 0;
} catch (RuntimeException runtimeException) {
runtimeException.printStackTrace();
con.rollback();
connection.rollback(conSavepoint);
}
}
}
1
huntagain2008 2022-05-25 13:49:46 +08:00
小白以为是连接问题,话说 catch 到的 异常是什么?
|
2
jimisun OP @huntagain2008 子方法异常控制父方法进行回滚
|