How can I avoid ResultSet is closed exception in Java?

前端 未结 10 1002
渐次进展
渐次进展 2020-11-28 09:51

As soon as my code gets to my while(rs.next()) loop it produces the ResultSet is closed exception. What causes this exception and how can I correct

相关标签:
10条回答
  • 2020-11-28 10:38

    Proper jdbc call should look something like:

    try { 
        Connection conn;
        Statement stmt;
        ResultSet rs; 
    
        try {
            conn = DriverManager.getConnection(myUrl,"",""); 
            stmt = conn.createStatement(); 
            rs = stmt.executeQuery(myQuery); 
    
            while ( rs.next() ) { 
                // process results
            } 
    
        } catch (SqlException e) { 
            System.err.println("Got an exception! "); 
            System.err.println(e.getMessage()); 
        } finally {
            // you should release your resources here
            if (rs != null) { 
                rs.close();
            }
    
            if (stmt != null) {
                stmt.close();
            }
    
            if (conn != null) {
                conn.close();
            }
        }
    } catch (SqlException e) {
        System.err.println("Got an exception! "); 
        System.err.println(e.getMessage()); 
    }
    

    you can close connection (or statement) only after you get result from result set. Safest way is to do it in finally block. However close() could also throe SqlException, hence the other try-catch block.

    0 讨论(0)
  • 2020-11-28 10:41

    A ResultSetClosedException could be thrown for two reasons.

    1.) You have opened another connection to the database without closing all other connections.

    2.) Your ResultSet may be returning no values. So when you try to access data from the ResultSet java will throw a ResultSetClosedException.

    0 讨论(0)
  • 2020-11-28 10:42

    Also, you can only have one result set open from each statement. So if you are iterating through two result sets at the same time, make sure they are executed on different statements. Opening a second result set on one statement will implicitly close the first. http://java.sun.com/javase/6/docs/api/java/sql/Statement.html

    0 讨论(0)
  • 2020-11-28 10:44

    I got same error everything was correct only i was using same statement interface object to execute and update the database. After separating i.e. using different objects of statement interface for updating and executing query i resolved this error. i.e. do get rid from this do not use same statement object for both updating and executing the query.

    0 讨论(0)
提交回复
热议问题