java.sql.SQLException: Operation not allowed after ResultSet closed

转自: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).

原文地址:https://www.cnblogs.com/sunseine/p/4057038.html