这样关闭我的连接资源有什么问题吗?我似乎在 postgres 运行中仍然有空闲连接。
public void doSomething(){
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
con = getConnection();
ps = con.prepareStatement("sql here");
....
rs = ps.executeQuery();
...
} catch(Exceptions stuff){
} finally {
closeAll(con,ps,rs);
}
}
public void closeAll(Connection con, PreparedStatement ps, ResultSet rs){
try{
if(rs != null){
rs.close();
}
if(ps != null){
ps.close();
}
if(con != null){
con.close();
}
} catch(SQLException e){
....
}
}
最佳答案
实践最佳实践
是的,他们以您关闭的方式关闭连接时存在问题。
假设,在关闭 ResultSet 对象时发生异常,其余的东西不会被关闭
其次,假设如果一切顺利,您仍然持有您未使用的其他连接(等),这会增加 JVM、数据库、内存管理器等的负担
建议使用 JAVA 7 中可用的“try(){} with resource”功能,或者如果您使用的是 JAVA 6,则在不再需要时关闭它们。
关于java - 在一次调用中关闭连接、PreparedStatement 和 ResultSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24440774/