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

标签 java jdbc

关闭 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/

相关文章:

java - 计算地点与用户位置之间的距离Android Studio

java - 多线程日志记录的简单方法

java - 缺少注释 : @Override is not shown by compiler in Eclipse IDE

java - 使用 JDBC 以用户定义的记录作为其 IN 参数调用 PL/SQL 过程

mysql - MySQL 中可以选择的行数有限制吗?

java - Spring 生成的 WSDL 公开了错误的协议(protocol)(HTTP 与 HTTPS)端点位置

java 。编写加载文件的最快方法

java - 如何在不更新旧记录的情况下使用 Hibernate session.save() 插入/保存对象

postgresql - Dataproc 尝试通过 JDBC 连接到 Postgres,缺少权限

java - 为什么语句有效但 java、jdbc、oracle 中的准备语句无效?