检查Java中的ResultSet是否为空

Max*_*ain 6 java jdbc hsqldb

我在我的程序中使用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);
}
Run Code Online (Sandbox Code Playgroud)

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

Ell*_*sch 12

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

或者,你可以保持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
}
Run Code Online (Sandbox Code Playgroud)