简体   繁体   English

如何在Java中两次使用同一结果集

[英]How to use a same resultset twice in Java

I would like to use same result set twice, once is to check whether it is empty and execute code based on the result, and then, using (resultset.next() the second result set will always skip a line because of the first result set 我想两次使用相同的结果集,一次是检查它是否为空并根据结果执行代码,然后,使用(resultset.next() ,第二个结果集将总是由于第一个结果而跳过一行组

Here's my code so far : 到目前为止,这是我的代码:

connection = DriverManager.getConnection(connection);
statement = (Statement) connection.createStatement();
resultset = statement.executeQuery(query);

String id = "0";
String idfromdb;

if(resultset.next() == false){
  System.out.println("table is empty")
  statement.executeUpdate(" INSERT INTO table VALUES ('value') ");
}

else{
  while(resultset.next()){
    idfromdb = resultset.getString("value")
    if(! idfromdb = id){
      System.out.println("no similar data has been found");
    }    
    else{
      System.out.println("similar data has been found");
    }
  }
}

When you call resultset.next() it will fetch one record,so you need to call previous() to reset the cursor 当您调用resultset.next() ,它将获取一条记录,因此您需要调用previous()来重置游标

The full code: 完整代码:

boolean hasRecord = true;
if(!resultset.next()){// you are missing ) here
    System.out.println("table is empty")
    statement.executeUpdate(" INSERT INTO table VALUES ('value') ");
    hasRecord = false;
}
if(hasRecord){
   resultset.previous();//move to the previous record
}

Change to do-while loop: 更改为do-while循环:

if(resultset.next() == false{
    System.out.println("table is empty")
    statement.executeUpdate(" INSERT INTO table VALUES ('value') ");
} else {
  do  {
    idfromdb = resultset.getString("value")
    if(! idfromdb = id){
        System.out.println("no similar data has been found");
    }

    else{
        System.out.println("similar data has been found");
    }
  } while(resultset.next());
}

do-while evaluates its expression at the bottom of the loop instead of the top. do-while在循环的底部而不是顶部评估其表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM