Retrieving Results of a Query


ResultSet rs = stmt.executeQuery( "SELECT name, password FROM users  where name='tim'"); while (rs.next( )) {     String name = rs.getString(1);     String password = rs.getString(2); }



A JDBC query returns a ResultSet object. A ResultSet represents a table of data containing the results of a database query. We can step through the ResultSet contents to get the results of the executed query. The ResultSet maintains a cursor that points to the current row of data. The ResultSet object has a next() method, which moves the cursor to the next row. The next() method will return false when there are no more rows in the ResultSet object. This makes it easy to use a while loop for stepping through all the rows contained within a ResultSet.

The ResultSet has getter methods for retrieving column values from the current row. Data values can be retrieved using either the index number of the column or the name of the column. Column numbering begins at 1. Column names as input to the getter methods are not case sensitive.

In this phrase, we obtain a ResultSet from executing a SELECT query. We loop through the rows contained within the ResultSet using the next() method and a while loop. We get name and password data values using the getString() method.

Remember, it is good practice to close your ResultSet instances when you are finished using them. A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net