结果集没有hasNext方法。我想检查resultSet是否有任何值
这条路对吗
if (!resultSet.next() ) {
System.out.println("no data");
}
结果集没有hasNext方法。我想检查resultSet是否有任何值
这条路对吗
if (!resultSet.next() ) {
System.out.println("no data");
}
当前回答
最初,结果集对象(rs)指向BFR(在第一条记录之前)。使用rs.next()后,光标指向第一条记录,rs值为“true”。使用while循环可以打印表中的所有记录。在检索到所有记录后,光标移动到ALR(在最后一条记录之后),它将被设置为null。让我们假设表中有2条记录。
if(rs.next()==false){
// there are no records found
}
while (rs.next()==true){
// print all the records of the table
}
简而言之,我们也可以将条件写成while (rs.next())。
其他回答
最好使用ResultSet.next()和do{…} while()语法。
“检查任何结果”调用ResultSet.next()将光标移动到第一行,因此使用do{…} while()语法来处理该行,同时继续处理循环返回的其余行。
通过这种方式,您可以检查任何结果,同时也可以处理返回的任何结果。
if(resultSet.next()) { // Checks for any results and moves cursor to first row,
do { // Use 'do...while' to process the first row, while continuing to process remaining rows
} while (resultSet.next());
}
提醒一句,
如果你使用的是org.springframework.jdbc.core.RowMapper 非常小心你是如何检查你的ResultSet是空的,因为 下面的语句适用于mapRow方法:
该方法不应该在ResultSet上调用next();它只应该映射当前行的值。<-来自文档
在这种情况下,你的支票可能会变成
resultSet.beforeFirst();
if (!resultSet.next() ) {
System.out.println("no data");
}
通过使用resultSet.next(),您可以轻松地获得结果,无论resultSet是否包含任何值
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet.next())
//resultSet contain some values
else
// empty resultSet
if (!resultSet.isAfterLast() ) {
System.out.println("No data");
}
isAfterLast()对于空结果集也返回false,但由于游标无论如何都在第一行之前,这个方法似乎更清楚。
我创建了以下方法来检查ResultSet是否为空。
public static boolean resultSetIsEmpty(ResultSet rs){
try {
// We point the last row
rs.last();
int rsRows=rs.getRow(); // get last row number
if (rsRows == 0) {
return true;
}
// It is necessary to back to top the pointer, so we can see all rows in our ResultSet object.
rs.beforeFirst();
return false;
}catch(SQLException ex){
return true;
}
}
有以下几点考虑是非常重要的:
CallableStatement对象必须设置为让to ResultSet对象走在末尾并返回到顶部。
TYPE_SCROLL_SENSITIVE: ResultSet对象可以移到末尾并返回顶部。进一步可以捕捉最后的变化。
CONCUR_READ_ONLY:可以读取ResultSet对象数据,但不能更新。
CallableStatement proc = dbconex.prepareCall(select, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);