Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java MySQL Iterate Backwards through ResultSet

Tags:

java

mysql

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.

like image 887
Scooter Avatar asked Apr 08 '26 15:04

Scooter


1 Answers

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_ONLYwhen 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

like image 101
Shreyas Chavan Avatar answered Apr 10 '26 03:04

Shreyas Chavan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!