如何将常见的JDBC惯用语法:创建/接收连接,查询数据库并可能处理结果与Java 7的自动资源管理try-with-resources语句集成?(教程)
在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...
块之外也无济于事,因为在 try 块之后你无法回滚,因为连接已经关闭了。 - home