不带事务的代码是这样的(外层的try-catch
已省略):
Connection conn = getConnection();
try {
Statement stmt = conn.createStatement();
stmt.executeUpdate(sql1);
stmt.executeUpdate(sql2);
} finally {
conn.close();
}
如果要添加事务,rollback
在哪里调用?
如果在catch
中调用,那么捕获哪个异常?如果仅仅捕获SQLException
,那么抛出其它异常的时候怎么办?如果捕获Exception
,那么抛出的异常目前没法处理(例如RuntimeException
)又怎么办?
如果在finally
中调用,我怎么区分正常和异常情况?
try (Connection conn = null) { conn.setAutoCommit(false); try (Statement stmt = conn.createStatement()) { stmt.executeUpdate(sql1); stmt.executeUpdate(sql2); conn.commit(); } catch (SQLException | RuntimeException e) { e.printStackTrace(); conn.rollback(); } } catch (SQLException e) { e.printStackTrace(); }
如果你觉得需要的话, 可以把RuntimeException
也rollback
了,但是上面的情况下,我觉得更应该考虑为什么会抛出RuntimeException
。
Exception
无法捕获RuntimeException
的吗?
JDBC
你只需要处理SQLException
即可
JDK1.7之后一个catch
块可以处理多个异常
try { // ... } catch(SQLException | RuntimeException e) { conn.rollback(); throw e; }