標籤:blog http io os ar 使用 java for sp
轉自:http://blog.csdn.net/hellobobantang/article/details/7173622
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1075)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:984)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:929)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:794)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:7145)
at org.xxx.similarity.Similarity.createIndexTable(Similarity.java:26)
at org.xxx.similarity.Similarity.main(Similarity.java:56)
百度這個問題,給出的解決方案都是:
一個stmt多個rs進行操作.那麼從stmt得到的rs1,必須馬上操作此rs1後,才能去得到另外的rs2,再對rs2操作.
不能互相交替使用,會引起rs已經關閉錯誤.錯誤的代碼如下:
stmt=conn.createStatement();
rs=stmt.executeQuery("select * fromt1");
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();
正確的代碼:
stmt=conn.createStatement();
rs=stmt.executeQuery("select * fromt1");
rs.last();//對rs的操作應馬上操作,操作完後再從資料庫得到rst,再對rst操作
rst=stmt.executeQuery("select * from t2");
rst.last();
當然這是導致這個錯誤的一種原因,但還有另外一個原因,請看如下代碼:
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/hellosql","root", "123");
stmt=conn.createStatement();
sql= "SELECT LAST_INSERT_ID()from"+tableName;
rs =stmt.executeQuery(sql);
while(rs.next()){
sql = "update "+tableName+" set notifyURL=‘"+URLUtil.getRequestServerContext(request) +"/NotifyAction?id="+rs.getInt(1)+"‘ where id ="+rs.getInt(1);
stmt.executeUpdate(sql);
}
rs.close();
rs =null;
stmt.close();
stmt =null;
con.close();
con =null;
原因是executeUpdate函數和execute函數會自動返回resultSet!
boolean java.sql.Statement.execute(String sql) throwsSQLException
Executes the given SQL statement, which may return multiple results. In some (uncommon) situations, a single SQL statement may return multiple result sets and/or update counts. Normally you can ignore this unless you are (1) executing a stored procedure that you know may return multiple results or (2) you are dynamically executing an unknown SQL string.
The execute
method executes an SQL statement and indicates the form of the first result. You must then use the methodsgetResultSet
orgetUpdateCount
to retrieve the result, andgetMoreResults
to move to any subsequent result(s).
java.sql.SQLException: Operation not allowed after ResultSet closed