【问题标题】:Resultset is empty when I close preparedStatement当我关闭preparedStatement 时结果集为空
【发布时间】:2017-09-30 07:07:59
【问题描述】:

我有这样的方法:

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 时resultSet 总是空的。 如果我用服装preparedStatement //selectQuery.close(); 注释掉这条线,一切都很好。 我为结果集赋值后关闭它。那为什么它是空的呢?

【问题讨论】:

标签: java jdbc resultset


【解决方案1】:

因为javadoc 是这么说的:

注意:当Statement 对象关闭时,其当前的ResultSet object(如果存在)也将关闭。

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

我很好奇您如何确定(关闭的)ResultSet 是“空的”。看起来关闭的ResultSet(除了close())上的所有操作都应该引发异常。

【讨论】:

    【解决方案2】:

    在检索结果集的数据之前,您不必关闭语句,否则这些数据可能无法访问。
    调用此方法时,其 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()) {
        // ...
    }
    

    【讨论】:

      【解决方案3】:

      您必须遍历 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);
      }
      

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          猜你喜欢
          • 2012-01-18
          • 1970-01-01
          • 2010-09-11
          • 2023-01-13
          • 1970-01-01
          • 1970-01-01
          • 2013-01-10
          • 2011-11-21
          相关资源
          最近更新 更多