Java Reference
In-Depth Information
String qry = "select recipe_num, name, description from
recipes";
Connection conn;
Statement stmt = null;
try {
conn = createConn.getConnection()
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(qry);
...
The same code can be more efficiently written as follows:
try (Connection conn = createConn.getConnection();
Statement stmt = conn.createStatement();) {
ResultSet rs = stmt.executeQuery(qry);
...
As you can see, the Statement object's executeQuery() method accepts a
string and returns a ResultSet object. The ResultSet object makes it easy to
work with the query results so that you can obtain the information you need in any or-
der. If you take a look at the next line of code in the example, a while -loop is created
on the ResultSet object. This loop will continue to call the ResultSet object's
next() method, obtaining the next row that is returned from the query with each iter-
ation. In this case, the ResultSet object is named rs , so while rs.next() returns
true, the loop will continue to be processed. Once all the returned rows have been pro-
cessed, rs.next() will return a false to indicate that there are no more rows to be
processed.
Within the while loop, each returned row is processed. The ResultSet object
is parsed to obtain the values of the given column names with each pass. Notice that if
the column is expected to return a string, you must call the ResultSet
getString() method, passing the column name in string format. Similarly, if the
column is expected to return an int , you'd call the ResultSet getInt() meth-
od, passing the column name in string format. The same holds true for the other data
types. These methods will return the corresponding column values. In the example in
the solution to this recipe, those values are stored into local variables.
Search WWH ::




Custom Search