Java generating query from resultSet and executing the new query

I am trying to use some query result to generate another query and execute the new query but that does not seem to work. The second query is not being executed. Can someone please tell me why? This is that part of the code.

Statment stmt = connnection.createStatement();
Statment stmt2 = connnection.createStatement();
ResultSet r =  stmt.executeQuery("Select * from employees");
while (r.next()) {
            String Str = "Select name from employees where employeeId = " + (r.getInt(3) + 1);
            System.out.println(str);
            query = stmt2.executeQuery(str);
            System.out.println(query.getString(1));}

The right query seems to be generated, but just won’t execute. Is there a reason why this is so. BTW “query” is declared as resultset. Thanks

Answer

you can only have one statement executing at one moment in time against one database connection — so you can either open another database connection and execute the second statement in the 2nd connection, or iterate through the resultset from first statement and store the employees database id’s (e.g. in an array/collection) then close that statement and run the second one, this time retrieving the id’s from the array/collection you saved them in.

Leave a Reply

Your email address will not be published. Required fields are marked *