我想两次使用相同结果集,一次是检查它是否为空并根据结果执行代码,然后使用(resultset.next()
,第二个结果集将总是因为第一个结果集而跳过一行
到目前为止,这是我的代码:
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");
}
}
}
答案 0 :(得分:2)
调用resultset.next()
时它将获取一条记录,因此您需要调用 previous() 重置光标
完整代码:
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
}
答案 1 :(得分:1)
更改为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在循环的底部而不是顶部评估其表达式。