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()){
}
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编程中使用MySQL时遇到的ResultSet关闭错误,并提供了避免该错误的方法。详细介绍了如何确保在执行SQL查询后立即操作ResultSet,以及在使用Statement执行更新查询时自动返回的ResultSet的正确处理方式。
2404

被折叠的 条评论
为什么被折叠?



