我正在使用以下方法在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已关闭
似乎我的真正问题出现在rs = takeFields.executeQuery()
之后/期间的第一个试块中 -
我在上述查询之后立即用一些System.out.println(rs.isClosed())
和System.out.println(takeFields.isClosed())
测试了它,并确认Prepared Statement takeFields实际上仍然是打开的,但结果集rs在查询执行后立即关闭。
我正在查看类似的问题并且我已经确认这个特定的Prepared Statement从未在其他任何地方使用或引用,并且它永远不会关闭,所以我想弄清楚为什么这个结果集会立即关闭以及如何让它合作。
答案 0 :(得分:3)
典型的处理结果集迭代器使用下一个方法调用,如下所示:
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