在用try-with-resource管理链接资源时,catch块中无法访问到connection,也就无法手动回滚
try (Connection con = createConnection()){
con.setAutoCommit(false);
Statement stm = con.createStatement();
stm.execute(someQuery); // causes SQLException
}catch(SQLException ex){
// 注意这里实际上无法访问到con
con.rollback();
// do other stuff
}
解决方案
try (Connection con = createConnection()){
con.setAutoCommit(false);
try (Statement stm = con.createStatement()) {
stm.execute(someQuery); // causes SQLException
}catch(SQLException ex){
con.rollback();
con.setAutoCommit(true);
throw ex;
}
con.commit();
con.setAutoCommit(true);
}
即将try-with-resource仅仅用作管理资源的,再设置一个try-catch来做catch。