Slide 14.31: Closing the result set and statement objects
  Slide 14.33: Committing changes
  Home


Making Changes to the Database


To write changes to the database, such as for INSERT or UPDATE operations, you will typically create a PreparedStatement object. Instead of calling the same statement over and over with different inputs, you can instead use a PreparedStatement, which allows you to execute a statement with varying sets of input parameters.

The java.sql.PreparedStatement interface allows binding parameters which are associating a parameter (indicated by a placeholder like ? in the prepared statement) with an actual Java value. Use setXXX( ) methods on the PreparedStatement object to bind data into the prepared statement to be sent to the database.

The following example shows how to use a prepared statement to execute INSERT operations that add two rows to the EMP table.

// Prepare to insert new names in the EMP table
PreparedStatement pstmt = 
  conn.prepareStatement(
    "insert into EMP( EMPNO, ENAME ) values( ?, ? )" );

// Add LESLIE as employee number 1500
pstmt.setInt( 1, 1500 );          // The first ? is for EMPNO
pstmt.setString( 2, "LESLIE" );   // The second ? is for ENAME

// Do the insertion
pstmt.execute( );

// Add MARSHA as employee number 507
pstmt.setInt( 1, 507 );           // The first ? is for EMPNO
pstmt.setString( 2, "MARSHA" );   // The second ? is for ENAME

// Do the insertion
pstmt.execute( );

// Close the statement
pstmt.close( );