Can we execute some queries while traversing resultset in java

后端 未结 4 693
春和景丽
春和景丽 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 16:54

    It doesn't happen like that, You can try until your query gets executed loop will wait.

    0 讨论(0)
  • 2021-01-05 16:58

    ideally you can only have one statement executing at one moment in time against one database connection so you can either create and execute the second statement, or iterate through the resultset from first statement and store the data in collection (e.g. in an arraylist of hashmap) then close that statement and run the second one, this time retrieving the id's from the collection you saved them in.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-05 17:12

    Each Statement can only have one open ResultSet at a time. From the documentation:

    By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.

    The calls to executeQuery inside your loop will implicitly close the outer ResultSet, so that's why you only see one row.

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