gpt4 book ai didi

java - java.sql.Connection.close() 对 java.sql.Statement 对象等的影响

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:57:30 24 4
gpt4 key购买 nike

关闭 java.sql.Connection 是否也会关闭从该连接获得的所有语句、准备语句等?或者,如果我关闭连接但未关闭语句等,是否会发生内存泄漏?

最佳答案

Does closing a java.sql.Connection also close all the statements, prepared statements, etc. obtained from that connection? Or is there going to be memory leak if I close the connection but leave the statements, etc. unclosed?

你不应该依赖它。

规范内容如下:

An application calls the method Statement.close to indicate that it has finished processing a statement. All Statement objects will be closed when the connection that created them is closed. However, it is good coding practice for applications to close statements as soon as they have finished processing them. This allows any external resources that the statement is using to be released immediately.

最佳做法是在 finally block 中关闭所有结果集、语句和连接,每个都包含在自己的 try/catch 中,以获取的相反顺序。

写一个这样的类:

public class DatabaseUtils
{
public static void close(Statement s)
{
try
{
if (s != null)
{
s.close();
}
}
catch (SQLException e)
{
// log or report in someway
e.printStackTrace();
}
}

// similar for ResultSet and Connection
}

这样调用:

Statement s;
try
{
// JDBC stuff here
}
finally
{
DatabaseUtils.close(s);
}

关于java - java.sql.Connection.close() 对 java.sql.Statement 对象等的影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2708689/

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