关于 ResultSet 的查询

Query regarding 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.getString(1).equalsIgnoreCase("1")){
         Step3
 }
}              while (rs.next());
}

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

您必须了解 next() 方法的具体作用。 next() 将光标移动到下一个元素。当你在里面写 next() if 条件已经通过并且没有更多的元素时 while.

为什么不通过

来简化代码
while ( rs.next() ) { 
   if (rs.getString(1).equalsIgnoreCase("0")){
          Step2
  }

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

如果进入while循环,则有项,否则无。

来自 JavaDoc ResultSet:

Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

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

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

现在,当调用 if(!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());
    }