在 Java 中检查 ResultSet 是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24398622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:59:02  来源:igfitidea点击:

Check if ResultSet is empty in Java

javajdbchsqldb

提问by Max Pain

I am using HSQLDB in my program. I want to check if my Result Set is empty or not.

我在我的程序中使用 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);
}

The above method is not working properly. According to this postI have to call .first()or .beforeFirst()to rest the cursor to the first row, but .first()and .beforFirst()are not supported in HSQL. I also tried to add connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);but I still get the same outcome (I get the message empty and the data from the DB!!!) What am I doing wrong here?

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

采纳答案by Elliott Frisch

If I understand your objective, you could use do whileloop

如果我理解你的目标,你可以使用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());
}

Or, you could just keep a countlike so,

或者,你可以保持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
}