结果集没有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())。

其他回答

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

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

根据最可行的答案,建议使用“isBeforeFirst()”。如果你没有“只转发类型”,这不是最好的解决方案。

有一个叫做".first()"的方法。要得到完全相同的结果,这就不那么过分了。您检查“结果集”中是否有内容,但没有移动光标。

文档声明:“(…)如果结果集中没有行则为false”。

if(rs.first()){
    //do stuff      
}

您也可以只调用isBeforeFirst()来测试是否有任何行返回而不移动游标,然后正常进行。- SnakeDoc 14年9月2日19:00

但是,"isBeforeFirst()"和"first()"是有区别的。首先,如果对“仅向前”类型的结果集执行操作,则会生成异常。

比较这两个throw部分: http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html isBeforeFirst () http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html第()

好的,基本上这意味着你应该使用“isBeforeFirst”,只要你有一个“仅转发”类型。否则,使用“first()”就不会那么夸张了。

你可以这样做

boolean found = false;

while ( resultSet.next() )
{
    found = true;
    resultSet.getString("column_name");
}

if (!found)
    System.out.println("No Data");
if (resultSet==null ) {
    System.out.println("no data");
}