Inserts, updates, and deletes using JDBC

The Statement object executes static SQL statements. You execute SQL statements such as INSERT, UPDATE, and DELETE, which do not return result sets, using the executeUpdate method of the Statement object. Statements such as CREATE TABLE and other data definition statements can also be executed using executeUpdate.

The following code fragment illustrates how JDBC carries out INSERT statements. It uses an internal connection held in the Connection object named conn. The code for inserting values from an external application using JDBC would need to use a different connection, but otherwise would be unchanged.

public static void InsertFixed()  {  
    // returns current connection
    conn = DriverManager.getConnection("jdbc:default:connection");
    // Disable autocommit
    conn.setAutoCommit( false );
    
    Statement stmt = conn.createStatement();
    
    Integer IRows = new Integer( stmt.executeUpdate
	   ("INSERT INTO Department (dept_id, dept_name )"
	    + "VALUES (201, 'Eastern Sales')" 
	     ) );
    // Print the number of rows updated
    System.out.println(IRows.toString() + "row inserted" );
  }

NoteSource code available This code fragment is part of the InsertFixed method of the JDBCExamples class, included in the ASIQ-12_7\Samples\ASA\JavaSQL\manual-examples subdirectory of your installation directory.

Notes

StepsRunning the JDBC Insert example

  1. Using Interactive SQL, connect to the sample database as user ID dba.

  2. Ensure the JDBCExamples class has been installed. It is installed together with the other Java examples classes.

    For instructions on installing the Java examples classes, see “Preparing for the examples”.

  3. Call the method as follows:

    CALL JDBCExamples>>InsertFixed()
    
  4. Confirm that a row has been added to the department table.

    SELECT *
    FROM department
    

    The row with ID 201 is not committed. You can execute a ROLLBACK statement to remove the row.

In this example, you have seen how to create a very simple JDBC class. Subsequent examples expand on this.