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

这条路对吗

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

当前回答

if (!resultSet.isAfterLast() ) {    
System.out.println("No data"); 
} 

isAfterLast()对于空结果集也返回false,但由于游标无论如何都在第一行之前,这个方法似乎更清楚。

其他回答

假设您正在使用一个新返回的ResultSet,其游标指向第一行之前,一个更简单的检查方法是调用isBeforeFirst()。这避免了在读取数据时必须回溯。

正如文档中解释的那样,如果游标不在第一条记录之前,或者结果集中没有行,则返回false。

if (!resultSet.isBeforeFirst() ) {    
    System.out.println("No data"); 
} 

 

if(resultSet.first) {

} else { 
    system.out.println("No raw or resultSet is empty");
}

因为如果ResultSet没有raw,那么ResultSet。第一个返回false。

为什么不使用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==null ) {
    System.out.println("no data");
}

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

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

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