Operation not allowed after closing ResultSet

I tried to find out the last two days.

Statement statement = con.createStatement(); String query = "SELECT * FROM sell"; ResultSet rs = query(query); while (rs.next()){//<--- I get there operation error here 

This is a request method.

  public static ResultSet query(String s) throws SQLException { try { if (s.toLowerCase().startsWith("select")) { if(stm == null) { createConnection(); } ResultSet rs = stm.executeQuery(s); return rs; } else { if(stm == null) { createConnection(); } stm.executeUpdate(s); } return null; } catch (Exception e) { e.printStackTrace(); con = null; stm = null; } return null; } 

How can I fix this error?

+6
source share
5 answers

It's hard to be sure only from the code you posted, but I suspect that the ResultSet inadvertently closes (or stm gets reused) inside the body of the while . This will throw an exception at the start of the next iteration.

In addition, you need to make sure that there are no other threads in the application that could potentially use the same DB connection or stm object.

+5
source

IMHO, you must do everything you need with a ResultSet before closing the connection.

+3
source

There are a few things you need to fix. Opening a connection, running a query to get rs, closing it and closing the connection, everything should be performed in the same function area as possible. from your code, you seem to use the "con" variable as a global variable that could potentially cause the problem. you do not close the stm object. or rs object. this code does not work for too long, even if it has no errors. Your code should look like this:

 if (stringUtils.isBlank(sql)){ throw new IllegalArgumentsException ("SQL statement is required"); } Connection con = null; PreparedStatement ps =null; Resultset rs = null; try{ con = getConnection(); ps = con.preparestatement(sql); rs = ps.executeQuery(); processResults(rs); close(rs); close(ps); close(con); }catch (Execption e){ log.Exception ("Error in: {}", sql, e); throw new RuntimeException (e); }finally{ close(rs); close(ps); close(con); } 
+2
source

use another Statement object in the inner loop How

 Statement st,st1; st=con.createStatement(); st1=con.createStatement(); //in Inner loop while(<<your code>>) { st1.executeQuery(<<your query>>); } 
+2
source

I know this is a few years later, but I found that synchronizing db methods usually fix this problem.

+1
source

Source: https://habr.com/ru/post/917529/


All Articles