How to check if resultset has records returned w/o moving the cursor in Java

有些话、适合烂在心里 提交于 2019-12-11 07:39:52

问题


I am wondering how to check if the resultset has some records returned, just like below,

while(((ResultSet) rs).next()){
    ((ResultSet) rs).previous();
    return true;
}

But I can't do this since the result set type is TYPE_FORWARD_ONLY, is there any handy API available for my case? wasNull is not the right one for certain, thank you for any pointers!

Even


回答1:


 if(!resultSet.isBeforeFirst()){
   System.out.println("resultset contin no rows");
 }

isBeforeFirst() returns true if the cursor is before the first row; false if the cursor is at any other position or the result set contains no rows




回答2:


The answer is, you can't. That the nature of SQL row sets: You are notified when you hit the end, but you don't know until you try to get the next record and there isn't one. It's just the way it is.




回答3:


If your first call to rs.next() is successful and it returned true, that means there are some records returned.




回答4:


Since you can not know before you make the rs.next() move about the state of your ResultSet you could probably:

  1. run a count statement before your create your ResultSet or

  2. do a first rs.next(), or rs.first() and use its contents in case your set is not empty like this:

            boolean state = rs.first(); // or rs.next();
            if (state == false)
                System.out.println("empty");
            else {
                System.out.println("not empty");
                while (state) {
                    System.out.println(rs.getInt(1));
                    // use your row ...
                    state = rs.next();
                }
            }
    


来源:https://stackoverflow.com/questions/6722285/how-to-check-if-resultset-has-records-returned-w-o-moving-the-cursor-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!