aspose file tools*
The moose likes JDBC and the fly likes It works, but why? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC
Bookmark "It works, but why?" Watch "It works, but why?" New topic
Author

It works, but why?

Cesar Sportore
Greenhorn

Joined: Sep 18, 2012
Posts: 6
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

Joined: Mar 07, 2010
Posts: 1672
    
    7

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: 171
    
    5

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
Greenhorn

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

Cheers!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: It works, but why?