gpt4 book ai didi

java - 即使我关闭 RS,结果集资源也会泄漏?

转载 作者:行者123 更新时间:2023-12-01 09:44:49 26 4
gpt4 key购买 nike

在我使用 rsHP = stmt.executeQuery(query); 的任何地方,都会收到“资源泄漏:‘rsHP’在此位置未关闭”的信息

这是此方法的基本布局...

public static void method(String x, Connection conn){
Statement stmtHP = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rsHP = null;

try{
----ALGORITHM IN HERE------
****This is the general form of this method*****

queryHP = "select * from SOMETABLE where SOMETHING = 'blah'";
rsHP = stmtHP.executeQuery(queryHP);

while(rsHP.next()){
List.add(rsHP.getString("COLNAME"));
}
.
.
repeats for 8 different queries
.
.
queryHP = "select * from SOMEOTHERTABLE where SOMETHINGELSE = 'blah2'";
rsHP = stmtHP.executeQuery(queryHP);

while(rsHP.next()){
List.add(rsHP.getString("NEWCOLNAME"));
}

}catch(Exception e){
System.out.println("Hey dumbo you suck, Exception Found");
rsHP.close();
stmtHP.close();
conn.close();
}finally{
rsHP.close();
stmtHP.close();
// connection gets closed later if no exceptions thrown
}

}// end method

最后,我显然要关闭我所有的东西。如果我的方法实际上不可能在抛出错误之外不关闭 RS 的情况下终止,我对如何发生内存泄漏感到困惑。

最佳答案

Connection#createStatement() 抛出 SQLException,因此此代码根本无法编译。

我建议你将方法的签名更改为

public static void method(String x, Connection conn) throws SQLException
<小时/>

对于资源泄漏,我想使用以下逻辑会对您有所帮助

try{
// code
rsHP.close();
conn.close();
}catch(Exception e){
// StackTrace
}finally{
if (rsHP != null) rsHP.close();
if (conn != null) conn.close();
}

关于java - 即使我关闭 RS,结果集资源也会泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38154816/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com