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

这条路对吗

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

当前回答

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内部重新执行查询是更好的选择。

其他回答

最好使用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());
}
ResultSet result = stmt.executeQuery(sqlQuery);
if (!result.next())
    status = "ERROR";
else
    status = "SUCCESS";

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

如果您想查看结果集中是否有任何行,这将起作用。

请注意,next()总是移动到下一行,因此如果您计划从结果集中进行任何读取操作,则需要考虑到这一点。

通常使用ResultSet(当简单读取时)是:

while (resultSet.next())
{
   ... read from the row here ...
}

如果已经调用next()一次来检查结果集是否为空,那么显然不能正确工作,所以要注意这一点。尽管存在用于“备份”的方法,但并非所有类型的结果集都支持这些方法。

最初,结果集对象(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())。