JDBC  «Prev  Next »

Lesson 9 Using a ResultSet
Objective Write code that uses values from a ResultSet object in HTML output.

Using ResultSet Object from JDBC

In init(), you opened a database connection.
At the start of doPost(), you read from that database into a result set. Now what? There are three important things you can do with a result set:
  1. Move to the next record from the database
  2. Get values from the record
  3. Close the result set

Move to next Record

To move to the next record, call the next() method of ResultSet. This method returns false if there is no next record. If you have not seen any records yet, it moves you to the first one. If there is at least one record, it returns true. If next() returns false the very first time you call it, there are no records in the result set, in other words no records in the database match the WHERE clause you provided in your SELECT statement.
To get values from the result set, call getString(), passing in the name of the field. You can pass these strings directly to println() to include them in your HTML, like this:

out.println("Hello " + name + ", your number is: " +
rs.getString("Number")");

You can use getString() to get any sort of information from the result set, whether it’s a string, a date, or a number. It will be converted to a string for you. When you’re finished with your result set, call its close() method to close it:
rs.close();
You should also close your statement object at the same point in your code:
stmt.close();
In the next lesson, you will learn how to write to a data source.