26.3.1.2. Using Statements to Execute SQL
Statement
objects allow you to execute
basic SQL queries and retrieve the results through the
ResultSet
class which is described later.
To create a Statement
instance, you call
the createStatement()
method on the
Connection
object you have retrieved via one
of the DriverManager.getConnection()
or
DataSource.getConnection()
methods
described earlier.
Once you have a Statement
instance, you
can execute a SELECT
query by calling the
executeQuery(String)
method with the SQL you
want to use.
To update data in the database, use the
executeUpdate(String SQL)
method. This method
returns the number of rows affected by the update statement.
If you don't know ahead of time whether the SQL statement will
be a SELECT
or an
UPDATE
/INSERT
, then you
can use the execute(String SQL)
method. This
method will return true if the SQL query was a
SELECT
, or false if it was an
UPDATE
, INSERT
, or
DELETE
statement. If the statement was a
SELECT
query, you can retrieve the results by
calling the getResultSet()
method. If the
statement was an UPDATE
,
INSERT
, or DELETE
statement, you can retrieve the affected rows count by calling
getUpdateCount()
on the
Statement
instance.
Example 26.2. Using java.sql.Statement to Execute a SELECT Query
// assume that conn is an already created JDBC connection
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT foo FROM bar");
// or alternatively, if you don't know ahead of time that
// the query will be a SELECT...
if (stmt.execute("SELECT foo FROM bar")) {
rs = stmt.getResultSet();
}
// Now do something with the ResultSet ....
} finally {
// it is a good idea to release
// resources in a finally{} block
// in reverse-order of their creation
// if they are no-longer needed
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) { // ignore }
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { // ignore }
stmt = null;
}
}