Reputation: 1079
I've executed a query that returns a ResultSet
of data that I would like to iterate backwards over. In a for loop it would look like this:
for (int i = MAX; i >=0; i--){
// do something
}
The only problem is I don't have a a column in my DB that is perfectly sequential, instead I have an id that is unique, but sometimes skips numbers. So, using the actual result set, is there some way I can do while(set.next()) {...}
but in reverse? Thanks.
Upvotes: 3
Views: 1808
Reputation: 1099
You can traverse a resultset backwards if you have a scrollable resultset.You can get this by doing
ResultSet.TYPE_SCROLL_INSENSITIVE
and ResultSet.CONCUR_READ_ONLY
when creating the statement.
Then you can use resultset.last() to get to the last entry and traverse backwards using resultset.previous()
Edit: If you want results in descending order of the non-sequential ids that you mentioned, you can retrieve the resultset in descending order by doing order by id desc
and then traverse the resultset normally
Upvotes: 6