我一直在对我们的宠物项目之一进行代码审查(主要使用像FindBugs这样的工具),FindBugs将以下代码标记为错误(伪代码):
Connection conn = dataSource.getConnection();
try{
PreparedStatement stmt = conn.prepareStatement();
//initialize the statement
stmt.execute();
ResultSet rs = stmt.getResultSet();
//get data
}finally{
conn.close();
}
Run Code Online (Sandbox Code Playgroud)
错误是此代码可能不会释放资源.我发现ResultSet和Statement没有关闭,所以我最后关闭了它们:
finally{
try{
rs.close()
}catch(SqlException se){
//log it
}
try{
stmt.close();
}catch(SqlException se){
//log it
}
conn.close();
}
Run Code Online (Sandbox Code Playgroud)
但是我在很多项目中遇到过上述模式(来自不少公司),没有人关闭ResultSet或Statements.
在Connection关闭时,您是否遇到没有关闭ResultSet和Statements的麻烦?
我发现只有这个,它指的是Oracle在关闭Connections时关闭ResultSet的问题(我们使用Oracle db,因此我的更正).java.sql.api在Connection.close()javadoc中什么也没说.