You can use a PreparedStatement object when an SQL statement is going to be run many times. A prepared statement is an SQL statement that has been precompiled.
This approach is more efficient than running the same statement multiple times using a Statement object, which compiles the statement each time it is run. In addition, the SQL statement contained in a PreparedStatement object may have one or more IN parameters. Use Connection.prepareStatement() to create PreparedStatement objects.
The PreparedStatement 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. For more information about using batch support, see Enhancements to JDBC support.
The following example shows how to use the PreparedStatement interface.
// Connect to the server.
Connection c = DriverManager.getConnection("jdbc:as400://mySystem");
// Create the PreparedStatement object. It precompiles the
// specified SQL statement. The question marks indicate where
// parameters must be set before the statement is run.
PreparedStatement ps =
c.prepareStatement("INSERT INTO MYLIBRARY.MYTABLE (NAME, ID) VALUES (?, ?)");
// Set parameters and run the statement.
ps.setString(1, "JOSH");
ps.setInt(2, 789);
ps.executeUpdate();
// Set parameters and run the statement again.
ps.setString(1, "DAVE");
ps.setInt(2, 456);
ps.executeUpdate();
// Close PreparedStatement and the Connection.
ps.close();
c.close();