Executing a JDBC Statement

The following code fragment provides the syntax for executing a SQL INSERT statement using JDBC:

java.sql.Statement statement = connection.createStatement( );
int rowsInserter = statement.executeUpdate( 
       "INSERT INTO authors(au_id, au_lname, au_fname, contract) " +
       " VALUES ('xyz', 'Brown', 'Emmit', 1)" );
statement.close( );
  1. Executing a SQL statement first requires the creation of a JDBC Statement object. A Statement object is produced by invoking the createStatement method on a valid JDBC Connection object:

    java.sql.Statement statement = connection.createStatement( );
  2. After a Statement object has been created, a SQL statement can be executed by invoking one of the execute methods found on the Statement object. For non-query statements, the executeUpdate method is the best method to use:

    statement.executeUpdate( "INSERT INTO authors(au_id, au_lname, " +
                             "au_fname, contract) VALUES " +
                             "('xyz', 'Brown', 'Emmit', 1)" );

    The executeUpdate method returns an int value indicating the number of rows inserted, updated, or deleted during the execution of the SQL statement. If the execution fails, you will get a SQLException.

  3. After the Statement object has been executed, it may be executed again, or freed by invoking the close method.

statement.close( );

Get SQL in a Nutshell, 2nd Edition 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.