Java ResultSet如何检查是否有任何结果

本文翻译自:Java ResultSet how to check if there are any results

Resultset has no method for hasNext. 结果集没有hasNext的方法。 I want to check if the resultSet has any value 我想检查resultSet是否有任何值

is this the correct way 这是正确的方法

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

#1楼

参考:https://stackoom.com/question/3db0/Java-ResultSet如何检查是否有任何结果


#2楼

if(resultSet.first) {

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

Because if ResultSet has no raw then resultSet.first returns false. 因为如果ResultSet没有raw,则resultSet.first返回false。


#3楼

Best to use ResultSet.next() along with the do {...} while() syntax for this. 最好使用ResultSet.next()以及do {...} while()语法。

The "check for any results" call ResultSet.next() moves the cursor to the first row, so use the do {...} while() syntax to process that row while continuing to process remaining rows returned by the loop. “检查任何结果”调用ResultSet.next()将光标移动到第一行,因此使用do {...} while()语法处理该行,同时继续处理循环返回的剩余行。

This way you get to check for any results, while at the same time also processing any results returned. 这样您就可以检查任何结果,同时还可以处理返回的任何结果。

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());
}

#4楼

ResultSet result = stmt.executeQuery(sqlQuery);
if (!result.next())
    status = "ERROR";
else
    status = "SUCCESS";

#5楼

To be totally sure of rather the resultset is empty or not regardless of cursor position, I would do something like this: 无论光标位置如何,要完全确定结果集是否为空,我会做这样的事情:

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

This function will return true if ResultSet is empty, false if not or throw an SQLException if that ResultSet is closed/uninitialized. 如果ResultSet为空,则此函数将返回true,否则返回false;如果ResultSet已关闭/未初始化,则返回SQLException。


#6楼

The best thing for to do is to check the first row so that when you intend to get the data you can avoid the mistake of skipping a row. 要做的最好的事情是检查第一行,这样当您打算获取数据时,可以避免跳过一行的错误。 Something like: if (!resultSet.first() ) { System.out.println("no data"); 类似于:if(!resultSet.first()){System.out.println(“no data”); } }

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值