我使用以下方法在 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 block 中的第一个 rs.getString() 行,声称 ResultSet 已关闭
看来我真正的问题发生在第一个 try block 中,即 rs = takeFields.executeQuery()
之后/期间。 -
我用一些System.out.println(rs.isClosed())
测试过它和System.out.println(takeFields.isClosed())
就在上述查询之后,并确认Prepared Statement takeFields实际上仍然打开,但结果集rs在查询执行后立即关闭。
我正在查看类似的问题,并且已确认此特定的准备好的语句从未在其他任何地方使用或引用,并且它从未关闭,因此我试图找出为什么此结果集立即关闭以及如何使其合作。
最佳答案
典型的处理结果集迭代器使用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
关于java - 执行查询后结果集立即关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50185583/