一個stmt多個rs進行操作引起的resultset已經關閉錯誤
一個stmt多個rs進行操作. 那麼從stmt得到的rs1,必須馬上操作此rs1後,才能去得到另外的rs2,再對rs2操作. 不能互相交替使用,會引起rs已經關閉錯誤. 錯誤的代碼如下: stmt=conn.createstatement();
rs=stmt.executequery("select * from t1");
rst=stmt.executequery("select * from t2");
rst.last();
rs.last();//由于執行了rst=stmt.executequery(sql_a);rs就會被關閉掉!是以程式執行到此會提示resultset
已經關閉.錯誤資訊為:java.sql.sqlexception: operation not allowed fter resultset closed
正确的代碼:
stmt=conn.createstatement();
rs.last();//對rs的操作應馬上操作,操作完後再從資料庫得到rst,再對rst操作
rst=stmt.executequery("select * from t2");
rst.last();
原因是: the object used for executing a static sql statement and returning the results it produces. 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.
一個stmt最好對應一個rs, 如果用一個時間内用一個stmt打開兩個rs同時操作,會出現這種情況. 是以解決此類問題:1.就多建立幾個stmt,一個stmt對應一個rs;2.若用一個stmt對應多個rs的話,那隻能得到一個rs後就操作,處理完第一個rs後再處理其他的,如上"正确代碼".
多個stmt對應各自的
rs. stmt=conn.createstatement();
stmt2=conn.createstatement();
rs=stmt.executequery("select * from t1");
rst=stmt2.executequery("select * from t2");
rs.last();