据说在使用完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 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();
}

其他回答

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

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

你所做的是完美的,非常好的练习。

我之所以说这是一种很好的实践……例如,如果由于某种原因,您正在使用“原始”类型的数据库池,并且调用connection.close(),连接将返回到池中,ResultSet/Statement将永远不会关闭,然后您将遇到许多不同的新问题!

所以你不能总是指望connection.close()来清理。

正确和安全的关闭与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();
}

如果你想要更紧凑的代码,我建议使用Apache Commons DbUtils。在这种情况下:

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 {
    DbUtils.closeQuietly(rs);
    DbUtils.closeQuietly(stmt);
    DbUtils.closeQuietly(conn);
}

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