如何集成创建/接收连接,查询数据库以及可能使用Java 7的自动资源管理(try-with-resources语句)处理结果的常用JDBC习惯用法?(教程)
在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();
}
Run Code Online (Sandbox Code Playgroud)
使用Java 7,您可以选择:
try(Connection con = getConnection(); PreparedStatement prep = con.prepareConnection("Update ..."){
...
con.commit();
}
Run Code Online (Sandbox Code Playgroud)
这将关闭Connection和PreparedStatement,但滚动呢?我无法添加包含回滚的catch子句,因为该连接仅在try块中可用.
你还在try块之外定义连接吗?这里的最佳做法是什么,尤其是在使用连接池的情况下?