我使用了一个返回特定行数的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
返回的行数?或者我必须写我自己的?
发布于 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");
}
发布于 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 ;
}
发布于 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());
}
https://stackoverflow.com/questions/8292256
复制相似问题