关闭 preparedStatement 时结果集为空

Resultset is empty when I close preparedStatement

我有这样的方法:

private static ResultSet select (Connection connection, String query) {
        PreparedStatement selectQuery = null;
        ResultSet resultSet = null;
        try {
            selectQuery = connection.prepareStatement(query);
            resultSet = selectQuery.executeQuery();
            selectQuery.close();
        } catch (SQLException e) {
            System.out.println(e);
        }
        return resultSet;
    }

问题是当我关闭 preparedStatement 时结果集总是空的。 如果我用 clothing preparedStatement //selectQuery.close(); 注释掉那一行,一切都很好。 我在 为 resultSet 赋值后关闭它。那为什么它是空的?

A ResultSet 与已执行的 Statement 关联。关闭语句和结果集,其中的所有数据都被清除。

您需要在关闭语句之前处理结果集,因此您的方法将不起作用。

因为javadoc是这么说的:

Note: When a Statement object is closed, its current ResultSet object, if one exists, is also closed.

基本原理:Statement.close() 规定的行为是释放所有资源。这些资源之一是用于读取结果的服务器端游标。但是如果你释放它,那么 ResultSet 就没有什么可以从中提取数据了。

我很好奇你是如何确定(关闭的)ResultSet 是 "empty"。看起来对关闭的 ResultSet(除了 close())的所有操作都应该抛出异常。

在检索到结果集的数据之前,您不必关闭语句,否则这些数据可能无法访问。
当您调用此方法时,其 ResultSet 对象将关闭。

因此,只有当您使用完一个语句后,才调用Statement.close()方法。

关闭应在 finally 语句中执行。
这样你就可以确保你不用担心什么时候关闭它。

使用您的实际代码:

private static ResultSet select (Connection connection, String query) {
        PreparedStatement selectQuery = null;
        ResultSet resultSet = null;
        try {
            selectQuery = connection.prepareStatement(query);
            resultSet = selectQuery.executeQuery();
        } catch (SQLException e) {
            System.out.println(e);
        }
        finally {
           if (selectQuery != null) { selectQuery.close(); }
        }
        return resultSet;
    }    
} 

更好的选择是使用 try-with-resources 语句:

try (Statement stmt = con.createStatement()) {
    // ...
}

您必须遍历 ResultSet。您在这里有一个高级示例:

try{ 
  // execute the query
  ResultSet rs = st.executeQuery(query);

  // iterate through the result set
  while (rs.next())
  {
    // Replace with your data
    int id = rs.getInt("id");
    String name = rs.getString("name");

    // do stuff with the result set, add to a List of objects (for example)
  }
  selectQuery.close();
}catch(SQLException e) {
        System.out.println(e);
}