Java Reference
In-Depth Information
If this all seems rather simplistic, well, it is. It may not be a very sophisti-
cated way of blending SQL with Java, but it is very effective. Notice that you
don't get any syntax checking on the SQL query when you write your program,
though it will throw an exception at runtime if you try to execute ungrammat-
ical SQL. For this reason it is not uncommon to try out all your SQL before-
hand, cutting and pasting the queries out of the SQL program that you use for
directly talking with your database. Some developers even like to keep their
queries in files, to be read at runtime. This has the added flexibility (and risk)
of being able to change the query without recompiling the code. Since the re-
compile doesn't provide any syntax checking on your query string anyway, it
seems a reasonable way to go, provided that you properly write-protect the files
containing the queries.
15.5
G ETTING R ESULTS
Returning to our example, we see that we can execute the query on the
Statement object and then get out the results:
ResultSet rs = stmt.executeQuery();
// read the results
while(rs.next()) {
int id = rs.getInt("id");
String pw = rs.getString("pw");
System.out.println("id="+id);
}
The results of a query are returned in a ResultSet object. The easiest way
to think of it is to consider it an iterator over the rows that result from the
query. In its simple form it is, like an iterator, a one-pass, once-through traversal
of the data. Since the result set is iterating over rows, we need to get at the indi-
vidual columns of results with a further method call on the ResultSet . You
can see that inside the while loop of the example.
The query was built to retrieve the columns id and pw from our table.
The getInt() and getString() methods use those column names to retrieve
the data from the ResultSet .
Search WWH ::




Custom Search