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 to execute an INSERT statement. It uses a Statement object that has been passed to the InsertStatic method as an argument.

public static void InsertStatic( Statement stmt )
{
  try
  {
    int iRows = stmt.executeUpdate(
      "INSERT INTO Departments (DepartmentID, DepartmentName)"
      + " VALUES (201, 'Eastern Sales')" );
    // Print the number of rows inserted
    System.out.println(iRows + " rows inserted");
  }
  catch (SQLException sqe)
  {
    System.out.println("Unexpected exception : " +
              sqe.toString() + ", sqlstate = " +
              sqe.getSQLState());
  }
  catch (Exception e)
  {
    e.printStackTrace();
  }
}
Source code available

This code fragment is part of the JDBCExample class included in the samples-dir\SQLAnywhere\JDBC directory.

Notes
  • The executeUpdate method returns an integer that reflects the number of rows affected by the operation. In this case, a successful INSERT would return a value of one (1).
  • When run as a server-side class, the output from System.out.println goes to the database server messages window.

To run the JDBC Insert example

  1. Using Interactive SQL, connect to the sample database as the DBA.

  2. Ensure the JDBCExample class has been installed.

    For more information about installing the Java examples classes, see Preparing for the examples.

  3. Define a stored procedure named JDBCExample that acts as a wrapper for the JDBCExample.main method in the class:

    CREATE PROCEDURE JDBCExample( IN arg CHAR(50) )
      EXTERNAL NAME 'JDBCExample.main([Ljava/lang/String;)V'
      LANGUAGE JAVA;
  4. Call the JDBCExample.main method as follows:

    CALL JDBCExample( 'insert' );

    The argument string 'insert' causes the InsertStatic method to be invoked.

  5. Confirm that a row has been added to the Departments table.

    SELECT * FROM Departments;

    The example program displays the updated contents of the Departments table in the database server messages window.

  6. There is a similar method in the example class called DeleteStatic that shows how to delete the row that has just been added. Call the JDBCExample.main method as follows:

    CALL JDBCExample( 'delete' );

    The argument string 'delete' causes the DeleteStatic method to be invoked.

  7. Confirm that the row has been deleted from the Departments table.

    SELECT * FROM Departments;

    The example program displays the updated contents of the Departments table in the database server messages window.