Retrieving results from a ResultSet object v42.5.1.2
A ResultSet
object is the primary storage mechanism for the data returned by a SQL statement. Each ResultSet
object contains both data and metadata in the form of a ResultSetMetaData
object. ResultSetMetaData
includes useful information about results returned by the SQL command: column names, column count, row count, column length, and so on.
To access the row data stored in a ResultSet
object, an application calls one or more getter
methods. A getter
method retrieves the value in a particular column of the current row. There are many different getter
methods. Each method returns a value of a particular type. For example, the getString()
method returns a STRING
type, the getDate()
method returns a Date
, and the getInt()
method returns an INT
type. When an application calls a getter
method, JDBC tries to convert the value into the requested type.
Each ResultSet
keeps an internal pointer that points to the current row. When the executeQuery()
method returns a ResultSet
, the pointer is positioned before the first row. If an application calls a getter
method before moving the pointer, the getter
method fails. To advance to the next (or first) row, call the ResultSet’s next()
method. ResultSet.next()
is a Boolean method. It returns TRUE
if there's another row in the ResultSet
or FALSE
if you moved past the last row.
After moving the pointer to the first row, the sample application uses the getString()
getter
method to retrieve the value in the first column and then prints that value. Since ListEmployees
calls rs.next()
and rs.getString()
in a loop, it processes each row in the result set. ListEmployees
exits the loop when rs.next()
moves the pointer past the last row and returns FALSE
.
When using the ResultSet
interface:
- You must call
next()
before reading any values.next()
returnstrue
if another row is available and prepares the row for processing. - Under the JDBC specification, an application must access each row in the
ResultSet
only once. It's safest to stick to this rule, although currently the EDB Postgres Advanced Server JDBC driver allows you to access a field as many times as you want. - When you finish using a
ResultSet
, call theclose()
method to free the resources held by that object.