据说在使用完JDBC资源后关闭所有资源是一个好习惯。但是如果我有下面的代码,是否有必要关闭Resultset和Statement?

Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
    conn = // Retrieve connection
    stmt = conn.prepareStatement(// Some SQL);
    rs = stmt.executeQuery();
} catch(Exception e) {
    // Error Handling
} finally {
    try { if (rs != null) rs.close(); } catch (Exception e) {};
    try { if (stmt != null) stmt.close(); } catch (Exception e) {};
    try { if (conn != null) conn.close(); } catch (Exception e) {};
}

问题是关闭连接是否有效,或者是否会留下一些可用的资源。


当前回答

据我所知,在当前的JDBC中,resultset和语句实现了AutoCloseable接口。这意味着它们会在被摧毁或超出范围时自动关闭。

其他回答

Java 1.7的try-with-resources语句使我们的工作变得更加简单。

try (Connection connection = dataSource.getConnection();
    Statement statement = connection.createStatement()) {
    try (ResultSet resultSet = statement.executeQuery("some query")) {
        // Do stuff with the result set.
    }
    try (ResultSet resultSet = statement.executeQuery("some query")) {
        // Do more stuff with the second result set.
    }
}

这个语法非常简洁和优雅。即使不能创建语句,连接也会被关闭。

正确和安全的关闭与JDBC this相关的资源的方法(摘自如何正确地关闭JDBC资源-每次):

Connection connection = dataSource.getConnection();
try {
    Statement statement = connection.createStatement();

    try {
        ResultSet resultSet = statement.executeQuery("some query");

        try {
            // Do stuff with the result set.
        } finally {
            resultSet.close();
        }
    } finally {
        statement.close();
    }
} finally {
    connection.close();
}

我现在使用Oracle和Java。以下是我的观点:

您应该显式地关闭ResultSet和Statement,因为Oracle以前在关闭连接后仍然保持游标打开的问题。如果您不关闭ResultSet(游标),它将抛出一个错误,如超过最大打开游标。

我认为您在使用其他数据库时可能会遇到同样的问题。

完成后关闭ResultSet:

完成时关闭ResultSet 完成后立即关闭ResultSet对象 使用ResultSet对象甚至 对象关闭 ResultSet对象 close,显式关闭ResultSet 给垃圾收集器机会 尽早回忆 因为ResultSet对象可能占用 大量内存取决于查询。 ResultSet.close ();

来自javadocs:

当一个Statement对象被关闭时,它的 当前ResultSet对象,如果有 存在,也是封闭的。

然而,当你关闭底层连接时,javadocs并不清楚Statement和ResultSet是否关闭。它们简单地声明关闭一个连接:

释放这个Connection对象的 数据库和JDBC资源 立即而不是等待 它们将被自动释放。

在我看来,当你用完ResultSets, Statements和Connections时,总是显式地关闭它们,因为close的实现在不同的数据库驱动程序中是不同的。

通过在Apache的DBUtils中使用closequiet等方法,可以节省大量的模板代码。

不,您不需要关闭连接以外的任何东西。根据JDBC规范,关闭任何较高的对象都会自动关闭较低的对象。关闭连接将关闭连接所创建的任何语句。关闭任何语句将关闭由该语句创建的所有结果集。连接是否可池并不重要。即使是可入池的连接也必须在返回池之前进行清洁。

当然,您可能在Connection上有很长的嵌套循环,创建了许多语句,然后关闭它们是合适的。虽然我几乎从来没有关闭ResultSet,但关闭语句或连接将关闭它们时似乎过度了。