Java Reference
In-Depth Information
When a ResultSet is returned from executeQuery() , it is positioned at the first record
that has been retrieved. The following methods of ResultSet can be used to pull infor-
mation from the current record:
getDate( String ) —Returns the Date value stored in the specified field name
(using the Date class in the java.sql package, not java.util.Date )
n
getDouble( String ) —Returns the double value stored in the specified field name
n
getFloat( String ) —Returns the float value stored in the specified field name
n
getInt( String ) —Returns the int value stored in the specified field name
n
getLong( String ) —Returns the long value stored in the specified field name
n
getString( String ) —Returns the String stored in the specified field name
n
These are just the simplest methods available in the ResultSet interface. The methods
you should use depend on the form that the field data takes in the database, although
methods such as getString() and getInt() can be more flexible in the information they
retrieve from a record.
You also can use an integer as the argument to any of these methods, such as
getString(5) , instead of a string. The integer indicates which field to retrieve (1 for the
first field, 2 for the second field, and so on).
18
An SQLException is thrown if a database error occurs as you try to retrieve information
from a resultset. You can call this exception's getSQLState() and getErrorCode()
methods to learn more about the error.
After you have pulled the information you need from a record, you can move to the next
record by calling the next() method of the ResultSet object. This method returns a
false Boolean value when it tries to move past the end of a resultset.
Normally, you can move through a resultset once from start to finish, after which you
can't retrieve its contents again.
When you're finished using a connection to a data source, you can close it by calling the
connection's close() method with no arguments.
Listing 18.1 contains the CoalReporter application, which uses the JDBC-ODBC bridge
and an SQL statement to retrieve some records from an energy database. Four fields are
retrieved from each record indicated by the SQL statement: FIPS , Country , Year , and
Anthracite Production . The resultset is sorted according to the Year field, and these
fields are displayed to standard output.
Search WWH ::




Custom Search