Using JDBC to Insert, Update, and Delete

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" );
  }
Note: This code fragment is part of the InsertFixed method of the JDBCExamples class. On Windows you can build this class using build.bat in C:\Documents and Settings\All Users\SybaseIQ\samples\SQLAnywhere\JDBC.
  • The setAutoCommit method turns off the AutoCommit behavior, so changes are only committed if you execute an explicit COMMIT instruction.

  • The executeUpdate method returns an integer, which reflects the number of rows affected by the operation. In this case, a successful INSERT would return a value of one (1).

  • The integer return type converts to an Integer object. The Integer class is a wrapper around the basic int data type, providing some useful methods such as toString().

  • The Integer IRows converts to a string to be printed. The output goes to the server window.