Java Reference
In-Depth Information
Statement
A Statement object is used for executing a static SQL statement and obtaining the
results it produces. Statement defines these three methods for executing SQL
statements, which handle SQL commands returning different kinds of results:
 
executeUpdate(String sql): Execute a SQL INSERT, UPDATE, or DELETE statement, which
returns either a count of rows affected or zero.
 
executeQuery(String sql): Execute a SQL statement that returns a single ResultSet.
 
execute(String sql): Execute a SQL statement that may return multiple results.
The executeUpdate method is used for SQL commands such as INSERT, UPDATE,
and DELETE, which return a count of rows affected rather than a ResultSet; or for
DDL commands such as CREATE TABLE, which returns nothing, in which case the
return value is zero.
The executeQuery method is used for SQL queries returning a single ResultSet. The
ResultSet object is discussed in detail later in this chapter.
A significant difference introduced in JDBC 3.0 is the ability for a Statement to have
more than one ResultSet open. If you are using a driver that does not implement
JDBC 3.0, a Statement can have only one ResultSet open at a time; if you need to
interleave data from different ResultSets, each must be generated by a different
Statement; otherwise, any execute method closes the current ResultSet prior to
executing.
The execute method is used to execute a SQL statement that may return multiple
results. In some situations, a single SQL statement may return multiple ResultSets
and/or update counts. The execute method returns boolean true if the SQL statement
returns a ResultSet and false if the return is an update count. The Statement object
defines the following supporting methods:
 
getMoreResults
 
getResultSet
 
getUpdateCount
These methods let you navigate through multiple results. You can use getResultSet()
or getUpdateCount() to retrieve the result and getMoreResults() to move to any
subsequent results.
An example of the use of a simple statement is shown in Listing 4-1 .
PreparedStatement
Search WWH ::




Custom Search