What is the logic behind results.next()?

ResultSet results = statement.executeQuery(sb.toString())) { List<Artists> artists = new ArrayList<>(); while(results.next()){     Artists artist = new Artists();     artist.setId(results.getInt(INDEX_ARTIST_ID));     artist.setName(results.getString(INDEX_ARTIST_NAME));     artists.add(artist); } return artists; 

I am trying to get all the records that is stored in results. If I reached the last element results.next() will be false. So how can be the last element added here? Can someone please explain clearly what is going on this loop?

Add Comment
1 Answer(s)

If the query returns e.g. 3 rows, your code will call next() 4 times.

On the first 3 calls it returns true, and the column values of the row is available through the getXxx() methods.

On the 4th call, next() returns false and no row is available, i.e. the getXxx() methods will throw exception if you try to call them.

This is all explained in the javadoc:

Moves the cursor forward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown.

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.