Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

It works, but why?

 
Cesar Sportore
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello coders,

I have this code right there(the language is Brazilian Portuguese):



Without the line resultados.next(), the console floods with exceptions...but why does the ResultSet needs it to work? Or is it the .executeQuery() method?
I'm still pretty green in Java, so I apologize if my question sounds lazy or stupid.

Thanks for any help!
Cheers!
 
Bill Gorder
Bartender
Posts: 1682
7
Android IntelliJ IDE Linux Mac OS X Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't see anything JPA related in your code snippet. I will edit your subject to remove the reference to JPA and move this topic to the JDBC forum for you. Welcome to the Ranch!
 
Tina Smith
Ranch Hand
Posts: 208
9
Eclipse IDE Firefox Browser Java
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the JavaDoc for ResultSet [emphasis mine]:
A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.


The ResultSet looks row by row at the data, and reads from the current row. Immediately after you query the db, your ResultSet doesn't have a current row yet, so you need to tell it to "get the next row for me please". If there are no rows, next() will return false and you can avoid any annoying "is this set empty" checking, or exception catching. This is convenient because results from a database are normally processed all at once in a loop.

The official JavaDoc is good documentation, and so useful that every time I type a Java class such as ResultSet, the forum admins have made it automatically link to the JavaDoc. Try it. It's awesome.

Welcome to the ranch!
 
Cesar Sportore
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a bunch Bill and Tina!
I'll be checking it out next time!

Cheers!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic