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

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).



  • 7
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值