Java 关于ResultSet的查询

Java 关于ResultSet的查询,java,jdbc,resultset,Java,Jdbc,Resultset,我正在执行语句查询并将数据存储在ResultSet rs中 // if no record is returned by the query if (!rs.next() ) { Step1 } // if atleast one record is returned by the query if(rs.next()){ do { if (rs.getString(1).equalsIgnoreCase("0")){ Step2 } if (rs.ge

我正在执行语句查询并将数据存储在ResultSet rs中

// if no record is returned by the query

if (!rs.next() ) {
Step1
}

// if atleast one record is returned by the query

if(rs.next()){
do {

  if (rs.getString(1).equalsIgnoreCase("0")){
          Step2
  }

  if (rs.getString(1).equalsIgnoreCase("1")){
         Step3
 }
}              while (rs.next());
}

但是,如果我只从查询中获得一条记录,则不会执行任何步骤。如果有人能指出错误,那将非常有帮助。

您必须了解
next()
方法的确切功能。next()将光标移动到下一个元素。当您在内部写入
next()
时,如果条件已通过,并且在
while
中没有更多元素

为什么不通过简单的操作来简化代码呢

while ( rs.next() ) { 
   if (rs.getString(1).equalsIgnoreCase("0")){
          Step2
  }

  if (rs.getString(1).equalsIgnoreCase("1")){
         Step3
 }
}
如果进入while循环,则会有项目,否则JavaDoc中的编号为:

将光标从当前位置向前移动一行。结果集光标最初位于第一行之前;对方法next的第一次调用使第一行成为当前行;第二个调用使第二行成为当前行,依此类推


在代码中,您不需要再次调用
rs.next()
,因为光标已经位于第一行。

最初
rs
包含一条记录,或者更精确地指向具有一条记录的结果集


现在,当
调用(!rs.next())
时,rs将移动到结果集中的下一条记录,该记录不存在,因为您只有一条记录。所以这一切进展顺利。但是,当您使用
if(rs.next())
时,
rs
将不会有任何记录,因此
if
将不会执行。

您总是跳过第一个元素,因为在获取元素之前要调用
.next()
两次。 尝试这样做:

if (rs.next()) {
    // At least one record returned
    do {
        if (rs.getString(1).equalsIgnoreCase("0")) {
            // Step2
        }

        if (rs.getString(1).equalsIgnoreCase("1")) {
            // Step3
        }
    } while (rs.next());
} else {
    // No records returned
}

您不应该调用
rs.next()
方法两次。以下逻辑应该起作用:

    if (!rs.next() ) {
       Step1
    }
    else{ // if atleast one record is returned by the query

        do {
          if (rs.getString(1).equalsIgnoreCase("0")){
                  Step2
          }
          if (rs.getString(1).equalsIgnoreCase("1")){
                 Step3
         }
        }while (rs.next());
    }

ResultSet
没有
hasNext()
methodNo,这在ResultSet中。注意:
if(condition)do{}while(condition)
,如果条件完全相同,则这与
while(condition){}
相同,除非您使用
else
来添加
步骤1