我用过一个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?或者我必须自己写?
Tu *_*ran 71
首先,您应该创建Statement哪个可以按命令移动游标:
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
然后检索ResultSet如下:
ResultSet rs = stmt.executeQuery(...);
将光标移动到最新一行并获取它:
if (rs.last()) {
    int rows = rs.getRow();
    // Move to beginning
    rs.beforeFirst();
    ...
}
然后rows变量将包含sql返回的行数
Jes*_*per 54
您可以使用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");
}
mpr*_*hat 26
一个简单的getRowCount方法可能如下所示:
private int getRowCount(ResultSet resultSet) {
    if (resultSet == null) {
        return 0;
    }
    try {
        resultSet.last();
        return resultSet.getRow();
    } catch (SQLException exp) {
        exp.printStackTrace();
    } finally {
        try {
            resultSet.beforeFirst();
        } catch (SQLException exp) {
            exp.printStackTrace();
        }
    }
    return 0;
}
只是要知道这个方法需要一个滚动敏感的resultSet,所以在创建连接时你必须指定scroll选项.默认值为FORWARD,使用此方法会引发异常.
另一种区分ResultSet中的0行或某些行的方法:
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 ;    
}
res.next()方法将指针指向下一行.在你的代码中你使用它两次,首先是if条件(光标移动到第一行)然后是while条件(光标移动到第二行).
因此,当您访问结果时,它从第二行开始.因此在结果中显示少一行.
你可以试试这个:
if(!res.next()){ 
    System.out.println("No Data Found");  
}
else{
    do{
       //your code
    } 
    while(res.next());
}