结果集没有hasNext方法。我想检查resultSet是否有任何值
这条路对吗
if (!resultSet.next() ) {
System.out.println("no data");
}
结果集没有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())。
其他回答
为了完全确定无论光标位置如何,结果集是否为空,我将这样做:
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下面的回答是这个问题的一个更优雅的解决方案。
我一直试图将当前行设置为第一个索引(处理主键)。我建议
if(rs.absolute(1)){
System.out.println("We have data");
} else {
System.out.println("No data");
}
填充ResultSet时,它指向第一行之前。当将它设置为第一行(由rs.absolute(1)表示)时,它将返回true,表示它成功地放置在第一行,如果该行不存在则返回false。我们可以推断
for(int i=1; rs.absolute(i); i++){
//Code
}
它将当前行设置为位置I,如果该行不存在,将失败。这是另一种方法
while(rs.next()){
//Code
}
为什么不使用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)”似乎工作得很好。
你可以这样做
boolean found = false;
while ( resultSet.next() )
{
found = true;
resultSet.getString("column_name");
}
if (!found)
System.out.println("No Data");