1. 程式人生 > >Operation not allowed after ResultSet closed--操作mysql資料庫

Operation not allowed after ResultSet closed--操作mysql資料庫

一個stmt多個rs進行操作.那麼從stmt得到的rs1,必須馬上操作此rs1後,才能去得到另外的rs2,再對rs2操作.不能互相交替使用,會引起rs已經關閉錯誤——Operation not allowed after ResultSet closed.

1

2

3

4

5

6

7

8

9

10

錯誤的程式碼如下:

 stmt=conn.createStatement();

 

 rs=stmt.executeQuery("select * from t1");

 rst=stmt.executeQuery("select * from t2"

);

 

 rs.last();

    //由於執行了rst=stmt.executeQuery(sql_a);rs就會被關閉掉!所以程式執行到此會提示ResultSet已經關閉.錯誤資訊為:java.sql.SQLException: Operation not allowed after ResultSet closed

 

rst.last();

正確的程式碼:

1

2

3

4

5

6

7

stmt=conn.createStatement();

 

rs=stmt.executeQuery("select * from t1");

rs.last();//對rs的操作應馬上操作,操作完後再從資料庫得到rst,再對rst操作

 

rst=stmt.executeQuery("select * from t2");

rst.last();

一個stmt最好對應一個rs, 如果用一個時間內用一個stmt開啟兩個rs同時操作,會出現這種情況.編寫這樣的程式碼的操作原則是:
所以解決此類問題:

  1.就多建立幾個stmt,一個stmt對應一個rs;

  2.若用一個stmt對應多個rs的話,那隻能得到一個rs後就操作,處理完第一個rs後再處理其他的,如上"正確程式碼".

 

1

2

3

4

5

6

7

8

9

多個stmt對應各自的rs.

stmt=conn.createStatement();

stmt2=conn.createStatement();

 

rs=stmt.executeQuery("select * from t1");

rst=stmt2.executeQuery("select * from t2");

 

rs.last();

rst.last();

  出處:http://haore147.cnblogs.com/