【问题标题】:Check if ResultSet is empty in Java [duplicate]检查Java中的ResultSet是否为空[重复]
【发布时间】:2014-08-15 10:09:40
【问题描述】:

我在我的程序中使用 HSQLDB。我想检查我的结果集是否为空。

//check if empty first
if(results.next() == false){
System.out.println("empty");
}

//display results
while (results.next()) {
String data = results.getString("first_name");
//name.setText(data);
System.out.println(data);
}

上述方法不能正常工作。根据这个post,我必须调用.first().beforeFirst() 将光标停留在第一行,但HSQL 不支持.first().beforFirst()。我还尝试添加connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); 但我仍然得到相同的结果(我得到了空的消息和来自数据库的数据!!!) 我在这里做错了什么?

【问题讨论】:

  • 有什么问题?观察:results.next() 第一次调用时将光标移动到第一行(在if 中)。因此,如果有数据,您的 while 循环的条件将在它开始有效地跳过第一行时将其移动到第二行。您可以改用 do-while 循环。
  • 您链接到的问题也有FORWARD_ONLY 结果集的答案(例如:接受的答案)。

标签: java jdbc hsqldb


【解决方案1】:

如果我理解您的目标,您可以使用 do while 循环

if (!results.next()) {
  System.out.println("empty");
} else {
  //display results
  do {
    String data = results.getString("first_name");
    //name.setText(data);
    System.out.println(data);
  } while (results.next());
}

或者,您可以像这样保留count

int count = 0;
//display results
while (results.next()) {
  String data = results.getString("first_name");
  //name.setText(data);
  System.out.println(data);
  count++;
}
if (count < 1) {
  // Didn't even read one row
}

【讨论】:

    猜你喜欢
    • 2011-01-20
    • 2016-09-23
    • 2020-02-03
    • 2013-05-11
    • 1970-01-01
    • 2013-01-21
    • 2012-01-09
    • 2021-08-12
    • 2018-04-18
    相关资源
    最近更新 更多