Search code examples
javamysqlloopsjdbc

Why does my SQL while(set.next()) skips the first element?


I execute:

select * from table_name order by column desc;

And I want to go through the items sequentially. I got the ResultSet from that and did:

while(set.next()) {
    // processing code
}

Unfortunately, that skips the very first element. What's the best way to iterate through the entire ResultSet and include the very first element?


Solution

  • Use:

    set.beforeFirst();
    while(set.next()) {
        // Your code
    }
    

    This will run the body of your loop once before advancing the ResultSet. You don't want to use a do loop (my previous answer) because it will throw an Exception if the query has 0 rows returned.