如何将创建/接收连接、查询数据库以及可能处理结果的常见 JDBC 习惯与 Java 7 的自动资源管理(try-with-resources 语句)集成? (Tutorial http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)
在 Java 7 之前,通常的模式是这样的:
Connection con = null;
PreparedStatement prep = null;
try{
con = getConnection();
prep = prep.prepareStatement("Update ...");
...
con.commit();
}
catch (SQLException e){
con.rollback();
throw e;
}
finally{
if (prep != null)
prep.close();
if (con != null)
con.close();
}
使用 Java 7,您可以:
try(Connection con = getConnection(); PreparedStatement prep = con.prepareConnection("Update ..."){
...
con.commit();
}
这将关闭Connection
和PreparedStatement
,但是回滚呢?我无法添加包含回滚的 catch 子句,因为连接仅在 try 块内可用。
您还在 try 块之外定义连接吗?这里的最佳实践是什么,特别是如果使用连接池?
try(Connection con = getConnection()) {
try (PreparedStatement prep = con.prepareConnection("Update ...")) {
//prep.doSomething();
//...
//etc
con.commit();
} catch (SQLException e) {
//any other actions necessary on failure
con.rollback();
//consider a re-throw, throwing a wrapping exception, etc
}
}
根据甲骨文文档 http://www.oracle.com/technetwork/articles/java/trywithresources-401775.html,您可以将 try-with-resources 块与常规 try 块结合起来。 IMO,上面的示例捕获了正确的逻辑,即:
- 如果没有出现问题,尝试关闭PreparedStatement
- 如果内部块出现问题,(无论是什么)回滚当前事务
- 无论如何尝试关闭连接
- 如果关闭连接时出现问题,您将无法回滚事务(因为这是连接上的一个方法,现在处于不确定状态),所以不要尝试
在 java 6 及更早版本中,我将使用一组三重嵌套的 try 块(外部 try-finally、中间 try-catch、内部 try-finally)来完成此操作。 ARM 语法确实使这个更简洁。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)