结果集没有hasNext方法。我想检查resultSet是否有任何值
这条路对吗
if (!resultSet.next() ) {
System.out.println("no data");
}
结果集没有hasNext方法。我想检查resultSet是否有任何值
这条路对吗
if (!resultSet.next() ) {
System.out.println("no data");
}
当前回答
我创建了以下方法来检查ResultSet是否为空。
public static boolean resultSetIsEmpty(ResultSet rs){
try {
// We point the last row
rs.last();
int rsRows=rs.getRow(); // get last row number
if (rsRows == 0) {
return true;
}
// It is necessary to back to top the pointer, so we can see all rows in our ResultSet object.
rs.beforeFirst();
return false;
}catch(SQLException ex){
return true;
}
}
有以下几点考虑是非常重要的:
CallableStatement对象必须设置为让to ResultSet对象走在末尾并返回到顶部。
TYPE_SCROLL_SENSITIVE: ResultSet对象可以移到末尾并返回顶部。进一步可以捕捉最后的变化。
CONCUR_READ_ONLY:可以读取ResultSet对象数据,但不能更新。
CallableStatement proc = dbconex.prepareCall(select, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
其他回答
我创建了以下方法来检查ResultSet是否为空。
public static boolean resultSetIsEmpty(ResultSet rs){
try {
// We point the last row
rs.last();
int rsRows=rs.getRow(); // get last row number
if (rsRows == 0) {
return true;
}
// It is necessary to back to top the pointer, so we can see all rows in our ResultSet object.
rs.beforeFirst();
return false;
}catch(SQLException ex){
return true;
}
}
有以下几点考虑是非常重要的:
CallableStatement对象必须设置为让to ResultSet对象走在末尾并返回到顶部。
TYPE_SCROLL_SENSITIVE: ResultSet对象可以移到末尾并返回顶部。进一步可以捕捉最后的变化。
CONCUR_READ_ONLY:可以读取ResultSet对象数据,但不能更新。
CallableStatement proc = dbconex.prepareCall(select, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
这是正确的,最初ResultSet的游标指向第一行之前,如果第一次调用next()返回false,则ResultSet中没有数据。
如果您使用这个方法,您可能必须立即调用beforeFirst()来重置它,因为它现在已经将自己定位到第一行之后。
然而,值得注意的是,Seifer下面的回答是这个问题的一个更优雅的解决方案。
ResultSet rs = rs.executeQuery();
if(rs.next())
{
rs = rs.executeQuery();
while(rs.next())
{
//do code part
}
}
else
{
//else if no result set
}
最好重新执行查询,因为当我们调用if(rs.next()){....} ResultSet的第一行将被执行,之后在while(rs.next()){....}我们将从下一行得到结果。因此,我认为在if内部重新执行查询是更好的选择。
为什么不使用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(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
}