Java MySQL Iterating backwards through ResultSet
I ran a query that returns ResultSet
data that I would like to retry. In a for loop, it looks like this:
for (int i = MAX; i >=0; i--){
// do something
}
The only problem is that I don't have a column in my DB that is perfectly consistent, instead I have a unique ID, but sometimes skips numbers. So, using an actual result set, is there some way to do it while(set.next()) {...}
, but vice versa? Thank.
source to share
You can move the result set backwards if you have a scrollable result set. You can get this by doing
ResultSet.TYPE_SCROLL_INSENSITIVE
and ResultSet.CONCUR_READ_ONLY
when creating an instruction.
Then you can use resultset.last () to go to the last entry and go back with resultset.previous ()
Edit: If you want to get the results in descending order of the non-sequential ids you mentioned, you can get the result set in descending order by doing order by id desc
and then in the usual way go to the result set
source to share