permaculture playing cards
The moose likes JDBC and Relational Databases and the fly likes It works, but why? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "It works, but why?" Watch "It works, but why?" New topic

It works, but why?

Cesar Sportore

Joined: Sep 18, 2012
Posts: 6
Hello coders,

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

Without the line, 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!
Bill Gorder

Joined: Mar 07, 2010
Posts: 1682

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!

[How To Ask Questions][Read before you PM me]
Tina Smith
Ranch Hand

Joined: Jul 21, 2011
Posts: 208

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!

Everything is theoretically impossible, until it is done. ~Robert A. Heinlein
Cesar Sportore

Joined: Sep 18, 2012
Posts: 6
Thanks a bunch Bill and Tina!
I'll be checking it out next time!

I agree. Here's the link:
subject: It works, but why?
It's not a secret anymore!