The executeQuery( ) Method
Now that you’ve learned how to insert,
update, and delete data in a table, it’s time to learn how to
use a SELECT statement to retrieve data. Whereas the
execute( ) and executeUpdate( )
methods discussed in previous sections return primitive data
types -- a boolean and int,
respectively -- the method normally used with a SELECT statement,
executeQuery( ), returns
a
ResultSet object. The executeQuery( ) method effectively combines the execute( ) and getResultSet( )
methods into one call:
ResultSet rset = null;
Statement stmt = null;
try {
stmt = conn.createStatement( );
rset = stmt.executeQuery("select last_name, first_name from person");
. . .
}In this example, we once again assume that a
Connection object, conn,
already exists. The example starts out by declaring a
ResultSet variable, rset, to
hold the reference to the ResultSet object
generated by the SQL statement. Next, it declares a
Statement variable, stmt, to
hold the reference to a Statement object. In the
try block, the Statement object
is created and stored in stmt using the
Connection object’s
createdStatement( ) method. Then, the
Statement object’s executeQuery( ) method is called to execute the SQL SELECT statement,
returning a ResultSet into
rset.
A ResultSet (which we will cover in great detail
in Chapter 10) is an object that has a set of accessor methods that allow you to get to the data returned from the database. These include methods for positioning the cursor, doing in-place updates, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access