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" ); }
Source code available This code fragment is part of the InsertFixed method of the JDBCExamples class, included in the /asa/javasubdirectory of your installation directory.
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.
Running the JDBC Insert example
Using Interactive SQL, connect to the sample
database as user ID dba
.
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”.
Call the method as follows:
CALL JDBCExamples>>InsertFixed()
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.