首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >获取Java中ResultSet返回的行数

获取Java中ResultSet返回的行数
EN

Stack Overflow用户
提问于 2011-11-28 14:33:02
回答 12查看 262.9K关注 0票数 73

我使用了一个返回特定行数的ResultSet。我的代码是这样的:

ResultSet res = getData();
if(!res.next())
{
    System.out.println("No Data Found");
}
while(res.next())
{
    // code to display the data in the table.
}

有没有什么方法可以检查ResultSet返回的行数?或者我必须写我自己的?

EN

回答 12

Stack Overflow用户

回答已采纳

发布于 2011-11-28 14:43:26

您可以使用do ... while循环而不是while循环,以便在执行循环后调用rs.next(),如下所示:

if (!rs.next()) {                            //if rs.next() returns false
                                             //then there are no rows.
    System.out.println("No records found");

}
else {
    do {
        // Get data from the current row and use it
    } while (rs.next());
}

或者在获得行数时自己计算行数:

int count = 0;

while (rs.next()) {
    ++count;
    // Get data from the current row and use it
}

if (count == 0) {
    System.out.println("No records found");
}
票数 64
EN

Stack Overflow用户

发布于 2012-06-26 18:54:00

区分0行或某些行与ResultSet的另一种方法:

ResultSet res = getData();

if(!res.isBeforeFirst()){          //res.isBeforeFirst() is true if the cursor
                                   //is before the first row.  If res contains
                                   //no rows, rs.isBeforeFirst() is false.

    System.out.println("0 rows");
}
else{
    while(res.next()){
        // code to display the rows in the table.
    }
}

如果您必须知道给定ResultSet的行数,下面是获取它的方法:

public int getRows(ResultSet res){
    int totalRows = 0;
    try {
        res.last();
        totalRows = res.getRow();
        res.beforeFirst();
    } 
    catch(Exception ex)  {
        return 0;
    }
    return totalRows ;    
}
票数 8
EN

Stack Overflow用户

发布于 2011-11-28 14:54:53

res.next()方法将获取指向下一行的指针。并且在代码中使用了两次,第一次用于if条件(游标移动到第一行),第二次用于while条件(游标移动到第二行)。

因此,当你访问你的结果时,它从第二行开始。所以在结果中显示少了一行。

您可以尝试这样做:

if(!res.next()){ 
    System.out.println("No Data Found");  
}
else{
    do{
       //your code
    } 
    while(res.next());
}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8292256

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档