Java Reference
In-Depth Information
that you need to use the
executeQuery()
method of the
Statement
object rather than the
execute()
method when you expect a
ResultSet
to be returned. Initially, the
ResultSet
's cursor
is positioned before the first row of the returned data, so you need to execute the
ResultSet.next()
method to point the cursor to the first row.
The
ResultSet.next()
method returns a
boolean false
if it advances the cursor beyond the end
of the
ResultSet.
This makes it suitable as the basis of a
WHILE
loop to loop through the entire
ResultSet
, as shown here in
Listing 7-1
.
Listing 7-1
also shows the use of
ResultSetMetaData
to
get the number of columns in the
ResultSet
.
Caution
ResultSet
columns count from 1, not from 0, so an exception will be thrown if you
forget this and try to use a loop which counts columns from column 0.
The
next section
continues the development of the JDBC Swing example started in
Chapters 5
and
6
,
adding the capability to execute queries.
A Swing-Based SQL Query Pane
To illustrate the topics covered in this chapter, the Swing-based Table Builder will be extended by the
addition of a Query Pane (see
Figure 7-7
). The Query Pane is based on components you built in
Chapter 5
. You will add a new View Menu to allow us to display the Query Pane, and a new
JInternalFrame for handling the Queries.
Figure 7-7:
SQL Query Pane
The View Menu
The View menu extends the DBMenu class, adding DBMenuItems for the ResultSet that you are
working with in this chapter.
Listing 7-2
shows the necessary code.
Listing 7-2: View menu with ResultSet item
package jdbc_bible.part2;