在下面的代码片段中,
1) try-catch block 是否在调用“conn.close()”之前自动调用“conn.rollback()”(通过 AutoClose)?
如果没有,我是否必须添加 finally { conn.rollback(); }
到那个 block ?
2) Connection对象传入bar()方法的方式,里面的try-catch方法是否正确?
public void foo() {
try (Connection conn = datasource.getConnection()) {
bar(conn, "arg");
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void bar(Connection conn, String args) throws SQLException {
try (PreparedStatement ps = conn.prepareStatement("SOME_QUERY")) {
// Do something
ps.executeUpdate();
} catch (SQLException err) {
throw err;
}
}
最佳答案
try-with-resources 将简单地调用 Connection
上的 close()
方法。调用效果Connection.close()
事务何时处于 Activity 状态是实现定义的:
It is strongly recommended that an application explicitly commits or rolls back an active transaction prior to calling the
close
method. If theclose
method is called and there is an active transaction, the results are implementation-defined.
换句话说:不要依赖它并显式调用 commit()
或 rollback()
因为实际行为会因驱动程序而异,甚至可能因版本而异同一个司机。
根据您的示例,我建议:
public void foo() {
try (Connection conn = datasource.getConnection()) {
bar(conn, "arg");
} catch (SQLException e) {
e.printStackTrace();
}
}
public void bar(Connection conn, String args) throws SQLException {
try (PreparedStatement ps = conn.prepareStatement("SOME_QUERY")) {
// Do something
ps.executeUpdate();
conn.commit();
} catch (SQLException err) {
conn.rollback();
throw err;
}
}
因为您不能在创建它的 try
的 catch
或 finally
block 中使用 conn
,你也可以嵌套它:
public void foo() {
try (Connection conn = datasource.getConnection()) {
try {
bar(conn, "arg");
conn.commit();
} catch (Exception ex) {
conn.rollback();
throw ex;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
关于使用 JDBC Connection 和 PreparedStatement 进行 Java 7 异常处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15685273/