本文翻译自: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”); } }