Running SQL statements with Statement objects
Use a Statement object to run an SQL statement and optionally obtain the ResultSet produced by it.
PreparedStatement inherits from Statement, and CallableStatement inherits from PreparedStatement. Use the following Statement objects to run different SQL statements:
- Statement interface: Runs a simple SQL statement that has no parameters.
- PreparedStatement interface - Runs a precompiled SQL statement that may or may not have IN parameters.
- CallableStatement interface - Runs a call to a database stored procedure. A CallableStatement may or may not have IN, OUT, and INOUT parameters.
The Statement object allows you to submit multiple SQL commands as a single group to a database through the use of batch support. You may improve performance by using batch support because processing a group of operations is typically faster than processing them one at a time.
When using batch updates, typically you turn off auto-commit. Turning off auto-commit allows your program to determine whether to commit the transaction if an error occurs and not all of the commands have executed. In JDBC 2.0 and later JDBC specifications, a Statement object can keep track of a list of commands that can be successfully submitted and executed together in a group. When this list of batch commands is executed by the executeBatch() method, the commands are executed in the order in which they were added to the list.
AS400JDBCStatement provides methods that enable you to perform many actions, including the following:
- Execute different kinds of statements
- Retrieve the values for different parameters of the Statement
object, including:
- The connection
- Any auto-generated keys created as a result of executing the Statement
- The fetch size and fetch direction
- The maximum field size and maximum row limit
- The current result set, the next result set, the type of result set, the result set concurrency, and the result set cursor holdability
- Add an SQL statement to the current batch
- Run the current batch of SQL statements
Statement interface
Use Connection.createStatement() to create new Statement objects.
The following example shows how to use a Statement object.
// Connect to the server.
Connection c = DriverManager.getConnection("jdbc:as400://mySystem");
// Create a Statement object.
Statement s = c.createStatement();
// Run an SQL statement that creates a table in the database.
s.executeUpdate("CREATE TABLE MYLIBRARY.MYTABLE (NAME VARCHAR(20), ID INTEGER)");
// Run an SQL statement that inserts a record into the table.
s.executeUpdate("INSERT INTO MYLIBRARY.MYTABLE (NAME, ID) VALUES ('DAVE', 123)");
// Run an SQL statement that inserts a record into the table.
s.executeUpdate("INSERT INTO MYLIBRARY.MYTABLE (NAME, ID) VALUES ('CINDY', 456)");
// Run an SQL query on the table.
ResultSet rs = s.executeQuery("SELECT * FROM MYLIBRARY.MYTABLE");
// Close the Statement and the Connection.
s.close();
c.close();