Java Reference
In-Depth Information
+ " ORDER BY balance DESC";
ResultSet results =
statement.executeQuery(selectRange);
(iv) String selectNames =
"SELECT * FROM Accounts WHERE surname < Jones'";
ResultSet results =
statement.executeQuery(selectNames);
Note the need for inverted commas around any string literals! (Speech marks
cannot be used, of course, since the opening of speech marks for a string within an
SQL query would be interpreted by the compiler as the closing of the query.)
Inverted commas are not required for numbers, but no error is generated if they
are used.
4. Manipulate/Display/Check Result(s)
The
ResultSet
object returned in response to a call of
executeQuery
contains
the database rows that satisfy the query's search criteria. The
ResultSet
interface
contains a
very
large number of methods for manipulating these rows, but the
majority of these will not be discussed here. [see Sect.
7.9
for coverage of some of
the other methods.] The only method that we need to make use of at present is
next
,
which moves the
ResultSet
cursor/pointer to the next row in the set of rows referred
to by that object.
Having moved to the particular row of interest via any of the above methods, we
can retrieve data via either the fi eld name or the fi eld position. In doing so, we must
use the appropriate
getXXX
method (where 'XXX' is replaced by the appropriate
Java type).
Examples
int getInt(String <columnName>)
int getInt(int <columnIndex>)
String getString(String <columnName>)
String getString(int <columnIndex>)
Similar methods exist for the other types, in particular
getFloat
,
getLong
and
getDate
. Note that the last of these is a method of class
java.sql.Date,
not of class
java.util.Date
. The latter is, in fact, a subclass of the former. Note also that the number
of a fi eld is its position
within a
ResultSet
row
, not its position within a database
row. Of course, if all fi elds of the database table have been selected by the query,
then these two will be the same. However, if only a subset of the fi elds has been
selected, they will not necessarily be the same!
Initially, the
ResultSet
cursor/pointer is positioned
before
the fi rst row of the
query results, so method
next
must be called before attempting to access the results.
Such rows are commonly processed via a
while
loop that checks the Boolean
return value of this method fi rst (to determine whether there is any data at the
selected position).
Search WWH ::
Custom Search