加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

检查Java中的ResultSet是否为空

发布时间:2020-12-14 05:36:34 所属栏目:Java 来源:网络整理
导读:参见英文答案 Java ResultSet how to check if there are any results21个 我在我的程序中使用HSQLDB.我想检查结果集是否为空. //check if empty firstif(results.next() == false){System.out.println("empty");}//display resultswhile (results.next()) {
参见英文答案 > Java ResultSet how to check if there are any results21个
我在我的程序中使用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);
但我仍然得到相同的结果(我得到消息为空,数据来自DB!)
我在这做错了什么?

解决方法

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

或者,你可以保持这样的计数,

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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读