The executeUpdate( ) Method
Now that we’ve created some tables using the execute( ) method, we can continue by using the
executeUpdate( )
method to insert, update, and delete
rows in those tables. The executeUpdate( ) method
works just like the execute( ) method, except that
it returns an integer value that reports the number of rows affected
by the SQL statement. The executeUpdate( ) method
effectively combines the execute( ) and
getUpdateCount( ) methods into one call:
int rslt = 0;
Statement stmt = null;
try {
stmt = conn.createStatement( );
rslt = stmt.executeUpdate("delete person");
. . .
}In this example, we once again assume that a
Connection object named conn
already exists. The example starts by declaring the
int variable rslt to hold the
number of rows affected 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 using the Connection object’s
createdStatement( ) method, and a reference to it
is stored in stmt. Then, the
Statement object’s executeUpdate( ) method is called to execute the SQL DELETE statement,
returning the number of rows affected into rslt.
Now that you have the general idea, let’s see the
executeUpdate( ) method in action.
Executing an INSERT, UPDATE, or DELETE Statement
Example 9-2, shows an insert
, update, and delete program which
uses the executeUpdate( ) method.
Example 9-2. An application to execute, insert, update, or delete DML
import java.io.*; ...
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