Can we execute some queries while traversing resultset in java

后端 未结 4 698
春和景丽
春和景丽 2021-01-05 16:30

I am trying to implement a task in java using JDBC like Stored Procedure in SQL. In SQL, when we write cursor, first we execute select query and then fetching the records we

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-05 17:06

    I would restructure your flow. Primarily, don't try and reuse the same Statement object to execute a new query. When I try that using the PostgreSQL driver, for example, I readily get an exception, "This ResultSet is closed."

    Instead, rewrite it to something like this:

    Connection conn = DriverManager.getConnection(...);
    Statement outerStatement = conn.createStatement();
    ResultSet outerResultSet = outerStatement.executeQuery("...");
    
    while (outerResultSet.next()) {
        Statement innerStatement = conn.createStatement();
        ResultSet innerResultSet = innerStatement.executeQuery("...");
        while (innerResultSet.next()) {
            // ...
        }
        innerResultSet.close();
        innerStatement.close();
    }
    outerResultSet.close();
    outerStatement.close();
    conn.close();
    

    Of course, surround with try-catch-finally as needed.

提交回复
热议问题