不带事务的代码是这样的(外层的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中调用,我怎么区分正常和异常情况?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
Exception无法捕获RuntimeException的吗?JDBC你只需要处理SQLException即可JDK1.7之后一个
catch块可以处理多个异常如果你觉得需要的话, 可以把
RuntimeException也rollback了,但是上面的情况下,我觉得更应该考虑为什么会抛出RuntimeException。