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.*; ...

Get Java Programming with Oracle JDBC now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.