执行查询后立即关闭结果集

ResultSet closing immediately after executing query

我正在使用以下方法在 JavaFX 应用程序中显示来自数据库的信息

public void showFirstSix() {
    PreparedStatement takeFields = null;
    ResultSet rs = null;
    String sqlTakeFields = "SELECT * FROM VirtualProductTable WHERE VirtualProductTable MATCH name=? ORDER BY rank DESC";
    try {
        takeFields = this.newSearchModel.connection.prepareStatement(sqlTakeFields);
        takeFields.setString(1, nameSearch.getText());
        rs = takeFields.executeQuery();
    } catch (SQLException e1) {
        e1.printStackTrace();
    }

    // gets a sorted list of matching products, next we just need to print them out entry by entry //
    // we'll traverse every row in the result set, and print all needed values before moving to the next row //

    try {

        // first entry
        String id = rs.getString(2);
        String name = rs.getString(3);
        String description = rs.getString(4);
        String price = rs.getString(5);
        String length = rs.getString(6);
        String width = rs.getString(7);
        String height = rs.getString(8);
        String dateAdded = rs.getString(9);
        Blob image = rs.getBlob(14);

        id1.setText(id);
        name1.setText(name);
        description1.setText(description);
        dateAdded1.setText(dateAdded);
        price1.setText(price);
        length1.setText(length);
        width1.setText(width);
        height1.setText(height);
        image1.setImage((Image) image);

        // second entry
        rs.next();

        id = rs.getString(2);
        name = rs.getString(3);
        description = rs.getString(4);
        price = rs.getString(5);
        length = rs.getString(6);
        width = rs.getString(7);
        height = rs.getString(8);
        dateAdded = rs.getString(9);
        image = rs.getBlob(14);

        id2.setText(id);
        name2.setText(name);
        description2.setText(description);
        dateAdded2.setText(dateAdded);
        price2.setText(price);
        length2.setText(length);
        width2.setText(width);
        height2.setText(height);
        image2.setImage((Image) image);

        ...

    } catch (SQLException e1) {
        e1.printStackTrace();
    } 

}

一旦执行此方法,我就会收到一个错误,指向第二个 try 块中的第一个 rs.getString() 行,声称 ResultSet 已关闭

看来我真正的问题出现在第一个 try 块中,立即 after/during rs = takeFields.executeQuery()- 我在上述查询之后用一些 System.out.println(rs.isClosed())System.out.println(takeFields.isClosed()) 测试了它,并确认 Prepared Statement takeFields 实际上仍然打开,但结果集 rs 在查询执行后立即关闭。

我正在查看类似的问题,并且我已经确认这个特定的 Prepared Statement 从未在其他任何地方使用或引用过,并且从未关闭过,所以我试图弄清楚为什么这个结果集会立即关闭并且怎么配合。

典型的处理结果集迭代器使用 next 方法调用,如下所示:

  ResultSet rs = stmt.executeQuery(query);
  while (rs.next()) {

    //read record
  }

在你的情况下,请确保在读取第一条记录之前调用下一个:

  ResultSet rs = stmt.executeQuery(query);
  if(! rs.next()) {
    return;
  }
  //read first reacord

   if(! rs.next()) {
    return;
  }
  //read second reacord