Using a ResultSet after executing two different queries with statement.executeQuery()

1.6k views Asked by At

Given the code below:

    //connection stuff
    ResultSet rs = statement.executeQuery(query1);

    statement.executeQuery(query2);

    while(rs.next){
       //code
    }

Is the result set rs still valid even though a second statement has been executed?

I know that when you close a statement the result set isn't valid any longer, but here the code is simply executing another query and not storing it in a result set.

1

There are 1 answers

1
copeg On BEST ANSWER

Presuming statement is a Statement, from the javadoc:

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 posted code is unsafe - the second call to executeQuery will return a new ResultSet, and given only one can be open at a time rs will not be valid.