Process PreparedStatements

Processing SQL statements with a PreparedStatement object is accomplished with the executeQuery, executeUpdate, and execute methods like Statement objects are processed. Unlike Statement versions, no parameters are passed on these methods because the SQL statement was already provided when the object was created. Because PreparedStatement extends Statement, applications can attempt to call versions of executeQuery, executeUpdate, and execute methods that take a SQL statement. Doing so results in an SQLException being thrown.

Return results from SQL queries

If an SQL query statement that returns a ResultSet object is to be processed, the executeQuery method should be used. The PreparedStatementExample program uses a PreparedStatement object's executeQuery method to obtain a ResultSet.

Note: If an SQL statement processed with the executeQuery method does not return a ResultSet, an SQLException is thrown.

Return update counts for SQL statements

If the SQL is known to be a Data Definition Language (DDL) statement or a Data Manipulation Language (DML) statement that returns an update count, the executeUpdate method should be used. The PreparedStatementExample sample program uses a PreparedStatement object's executeUpdate method.

Process SQL statements where the expected return is unknown

If the SQL statement type is not known, the execute method should be used. Once this method has been processed, the JDBC driver can tell the application what results types the SQL statement generated through API calls. The execute method returns true if the result is at least one ResultSet and false if the return value is an update count. Given this information, applications can use the getUpdateCount or getResultSet statement methods to retrieve the return value from processing the SQL statement.

Note: Calling the getUpdateCount method when the result is a ResultSet returns -1. Calling the getResultSet method when the result is an update count returns null.

Related concepts
Create and use PreparedStatements
Related reference
Example: Use PreparedStatement to obtain a ResultSet