JDBC: How to clear the contents of a result set before using it again?

Solace picture Solace · Apr 26, 2014 · Viewed 8.7k times · Source

I want to clear the contents of a result set (but nothing should happen to the underlying database) before using it again to execute a new query?

Is there any method which will delete its data (but do nothing to the underlying database, that's important), so that I can use the same resultset again to retrieve data from another query?

A quick search in the API documentation gave me the idea that deleting things through a method like deleteRow() will actually delete data from the database as well. I just want to reset/refresh/clear the resultSet, so that when it is again used to get results of another query, it should contain data from that query only, and not the previous one.

Or does it automatically remove its contents itself once we have retrieved them from it (through methods like ResultSet.getInt(), ResultSet.getString() etc.)

EDIT:- Can we create new result sets for executing each query in the same method?

Answer

geoand picture geoand · Apr 26, 2014

Lets say you want to execute a query like this :

ResultSet rs = statement.executeQuery("select * from people");

You would iterate of the results with something like this:

while(result.next()) {
    // ... get column values from this record
}

Then you just reuse the variable rs to execute another query like:

rs = statement2.executeQuery("select * from cars");

Here is a tutorial on working with ResultSet