java 无效状态,ResultSet 对象已关闭
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7263240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Invalid state, the ResultSet object is closed
提问by Mike
I am running the code, however am getting a "Invalid state, the ResultSet object is closed." error. What is causing the error?
我正在运行代码,但是收到“无效状态,ResultSet 对象已关闭”。错误。导致错误的原因是什么?
try{
query = "SELECT * FROM BUNDLE_TEMP "
+ "MINUS "
+ "SELECT * FROM BUNDLE";
rs = stmt.executeQuery(query);
while (rs.next()){
String bundle = rs.getString("BUNDLE");
String week = rs.getString("WEEK");
String sched_dt = rs.getString("SCHED_DT").replace(" 00:00:00.0", "");
String dropper_id = rs.getString("DROPPER_ID");
query = "INSERT INTO BUNDLE "
+ "VALUES ('"
+ bundle+"','"
+ week+"','"
+ sched_dt+"','"
+ dropper_id+"')";
stmt.executeUpdate(query);
}
}catch(Exception e){
System.out.println("Error while trying to insert into BUNDLE\n"+query+"\n"+ e);
}
回答by Philipp Reichart
You cannot execute another SQL query on the same Statement
you're currently iterating over with a ResultSet
. Doing this will close the previously open cursor (your SELECT
query resp. ResultSet
):
您不能Statement
在当前使用ResultSet
. 这样做将关闭先前打开的游标(您的SELECT
查询响应ResultSet
):
To quote the API docs for Statement:
By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.
默认情况下,每个 Statement 对象只能同时打开一个 ResultSet 对象。因此,如果一个 ResultSet 对象的读取与另一个的读取交错,则每个对象都必须由不同的 Statement 对象生成。如果存在打开的对象,则 Statement 接口中的所有执行方法都会隐式关闭语句的当前 ResultSet 对象。
Create another Statement
instance from your Connection
, let's call it updateStmt
and executeUpdate()
on that one.
Statement
从您的 中创建另一个实例Connection
,让我们调用它updateStmt
并executeUpdate()
在该实例上调用它。
Also, look into Prepared Statementsfor your update, it will probably be more performant and secure.
此外,查看准备好的语句以进行更新,它可能会更高效和安全。