java jdbc accessing multiple resultsets

后端 未结 3 1766
既然无缘
既然无缘 2020-12-18 14:54

I have the following structure:

List -->List_Participant -->Participant

so a list may contain several participants.I try to read this in java:



        
相关标签:
3条回答
  • 2020-12-18 15:45

    Nested query ? Something like Select * from List_Participant where name in (select name from List); This can be made to work for your third tabel as well.

    0 讨论(0)
  • 2020-12-18 15:47

    Here is the reason why you can't have two ResultSet opened from the same Statement

    ResultSet javadoc :

    A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.

    So basicly, a Statement can only give you one ResultSet at a time, so you loose the first result when you execute the second query.

    Solution :

    • Using one instance of Statement per ResultSet needed.
    • merging the queries to only have one
    0 讨论(0)
  • 2020-12-18 15:57

    You can try using two different Statement instances for each query. See the JavaDoc for java.sql.Statement. The following example shows the principle.

        Statement statement1 = connection.createStatement();
        Statement statement2 = connection.createStatement();
    
        ResultSet resultSet1 = statement1.executeQuery("select * from list");
        while(resultSet1.next()){
            String name = resultSet1.getString("Name");
    
            ResultSet resultSet2 = statement2.executeQuery("select * from List_Participant where name= '"+name+"'");
            while(resultSet2.next()){
                // get the participants
            }
        }
    

    BUT: This is not standard usage of JDBC or SQL for good reasons. It deprives the database of any optimization possibility and moves to much data between the DB and your app for no good reason (See the comments of JohnSkeet and BalusC).

    Better use appropriate JOINsin your one and only statement. This can be optimized by the DB:

    SELECT lp.* FROM list l JOIN List_Participant lp ON l.name = lp.name
    

    Add any filters/conditions you like to minimize the data retrieved.

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