Java Reference
In-Depth Information
constant integer from class
Types
(package
java.sql
) indicating the type of a specified
column. Programs can use these values in a
switch
statement to invoke
ResultSet
methods that return the column values as appropriate Java types. For example, if the type
of a column is
Types.INTEGER
,
ResultSet
method
getInt
can be used to get the column
value as an
int
. For simplicity, this example treats each value as an
Object
. We retrieve
each column value with
ResultSet
method
getObject
(line 40), then print the
Object
's
String
representation.
ResultSet
get
methods typically receive as an argument either a
column number (as an
int
) or a column name (as a
String
) indicating which column's
value to obtain. Unlike array indices,
ResultSet
column numbers start at 1
.
Performance Tip 24.1
If a query specifies the exact columns to select from the database, the
ResultSet
contains
the columns in the specified order. In this case, using the column number to obtain the
column's value is more efficient than using the column name. The column number pro-
vides direct access to the specified column. Using the column name requires a search of the
column names to locate the appropriate column.
Error-Prevention Tip 24.1
Using column names to obtain values from a
ResultSet
produces code that is less error
prone than obtaining values by column number—you don't need to remember the col-
umn order. Also, if the column order changes, your code does not have to change.
Common Programming Error 24.6
Specifying column index 0 when obtaining values from a
ResultSet
causes a
SQL-
Exception
—the first column index in a
ResultSet
is always 1.
When the end of the
try
block is reached (line 43), the close method is called on the
ResultSet
,
Statement
and
Connection
that were obtained by the
try
-with-resources
statement.
Common Programming Error 24.7
A
SQLException
occurs if you attempt to manipulate a
ResultSet
after closing the
Statement
that created it. The
ResultSet
is discarded when the
Statement
is closed.
Software Engineering Observation 24.5
Each
Statement
object can open only one
ResultSet
object at a time. When a
Statement
returns a new
ResultSet
, the
Statement
closes the prior
ResultSet
. To use multiple
ResultSet
s in parallel, separate
Statement
objects must return the
ResultSet
s.
The next example (Figs. 24.25 and 24.28) allows the user to enter any query into the pro-
gram. The example displays the result of a query in a
JTable
, using a
TableModel
object
to provide the
ResultSet
data to the
JTable
. A
JTable
is a swing GUI component that
can be bound to a database to display the results of a query. Class
ResultSetTableModel
(Fig. 24.25) performs the connection to the database via a
TableModel
and maintains the
ResultSet
. Class
DisplayQueryResults
(Fig. 24.28) creates the GUI and specifies an in-
stance of class
ResultSetTableModel
to provide data for the
JTable
.