结果集没有hasNext方法。我想检查resultSet是否有任何值

这条路对吗

if (!resultSet.next() ) {
    System.out.println("no data");
} 

当前回答

为了完全确定无论光标位置如何,结果集是否为空,我将这样做:

public static boolean isMyResultSetEmpty(ResultSet rs) throws SQLException {
    return (!rs.isBeforeFirst() && rs.getRow() == 0);
}

如果ResultSet为空,此函数将返回true;如果ResultSet为空,则返回false;如果ResultSet为关闭/未初始化,则抛出SQLException。

其他回答

这是正确的,最初ResultSet的游标指向第一行之前,如果第一次调用next()返回false,则ResultSet中没有数据。

如果您使用这个方法,您可能必须立即调用beforeFirst()来重置它,因为它现在已经将自己定位到第一行之后。

然而,值得注意的是,Seifer下面的回答是这个问题的一个更优雅的解决方案。

我认为检查结果集最简单的方法是通过包org.apache.commons.collections.CollectionUtils下的CollectionUtils

if(CollectionUtils.isNotEmpty(resultList)){
  /**
  * do some stuff
  */
}

这将检查null以及空结果集条件。

有关更详细的信息,您可以参考下面的文档。 CollectionUtils

你通常会这样做:

while ( resultSet.next() ) { 
   // Read the next item
   resultSet.getString("columnName");
}

如果要报告一个空集,请添加一个变量来计算读取的项。如果您只需要阅读一个项目,那么您的代码就足够了。

最好的方法是检查第一行,这样当您打算获取数据时就可以避免跳过一行的错误。类似于:if (!resultSet.first()) {System.out。println(没有数据);}

为什么不使用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)”似乎工作得很好。