结果集没有hasNext方法。我想检查resultSet是否有任何值
这条路对吗
if (!resultSet.next() ) {
System.out.println("no data");
}
结果集没有hasNext方法。我想检查resultSet是否有任何值
这条路对吗
if (!resultSet.next() ) {
System.out.println("no data");
}
当前回答
我相信这是一篇实用且易于阅读的文章。
if (res.next()) {
do {
// successfully in. do the right things.
} while (res.next());
} else {
// no results back. warn the user.
}
其他回答
为什么不使用rs.getRow()?
int getRow()
throws SQLException
Retrieves the current row number. The first row is number 1, the second number 2, and so on.
Note:Support for the getRow method is optional for ResultSets with a result set type of TYPE_FORWARD_ONLY
Returns:
the current row number; 0 if there is no current row
Throws:
SQLException - if a database access error occurs or this method is called on a closed result set
SQLFeatureNotSupportedException - if the JDBC driver does not support this method
Since:
1.2
对我来说,检查“if (rs.getRow() != 0)”似乎工作得很好。
if (!resultSet.isAfterLast() ) {
System.out.println("No data");
}
isAfterLast()对于空结果集也返回false,但由于游标无论如何都在第一行之前,这个方法似乎更清楚。
假设您正在使用一个新返回的ResultSet,其游标指向第一行之前,一个更简单的检查方法是调用isBeforeFirst()。这避免了在读取数据时必须回溯。
正如文档中解释的那样,如果游标不在第一条记录之前,或者结果集中没有行,则返回false。
if (!resultSet.isBeforeFirst() ) {
System.out.println("No data");
}
我认为检查结果集最简单的方法是通过包org.apache.commons.collections.CollectionUtils下的CollectionUtils
if(CollectionUtils.isNotEmpty(resultList)){
/**
* do some stuff
*/
}
这将检查null以及空结果集条件。
有关更详细的信息,您可以参考下面的文档。 CollectionUtils
ResultSet rs = rs.executeQuery();
if(rs.next())
{
rs = rs.executeQuery();
while(rs.next())
{
//do code part
}
}
else
{
//else if no result set
}
最好重新执行查询,因为当我们调用if(rs.next()){....} ResultSet的第一行将被执行,之后在while(rs.next()){....}我们将从下一行得到结果。因此,我认为在if内部重新执行查询是更好的选择。