A java.sql.Statement sends SQL to the server and exposes its current result or update count. Use a PreparedStatement when SQL contains application data.
Execution and results
| Method | Behavior |
|---|---|
executeQuery(sql) |
Returns a single relational ResultSet. Raises SQLException if the command has no relational result set. |
executeUpdate(sql) |
Executes a statement that produces an update count or no row set, such as INSERT or CREATE TABLE. Returns the scalar count as an int. |
execute(sql) |
Returns true when the current result is a ResultSet and false when it is an update count. |
getResultSet() |
Returns the current result set or null. |
getUpdateCount(), getLargeUpdateCount() |
Return the current update count or -1 when there is none. The large version returns a long. |
getMoreResults(), getMoreResults(Statement.CLOSE_CURRENT_RESULT) |
Close the current result and return false. The driver exposes at most one result per statement execution. The other result retention flags are unsupported. |
addBatch(sql), clearBatch() |
Queue an SQL command that produces an update count, or clear queued commands. |
executeBatch(), executeLargeBatch() |
Send queued SQL updates and return counts in batch order as int[] or long[]. The driver clears the queue after execution. |
executeLargeUpdate(sql) |
Executes an update and returns the count as a long. |
getGeneratedKeys() and generated-key overloads of execute, executeUpdate and executeLargeUpdate |
Request and read generated keys when the server supports them. See generated keys. |
Reusing a statement closes its previous result. Close or consume a result before executing another command on the same statement.
Generated keys
Check connection.getMetaData().supportsGetGeneratedKeys() before requesting keys. Pass Statement.RETURN_GENERATED_KEYS to return identity values generated by the insert, or Statement.NO_GENERATED_KEYS to skip key retrieval. The String[] and int[] overloads select target table columns by name or one-based position and return them in request order. Read the resulting ResultSet before reusing the statement or committing the transaction.
This example assumes public.orders has an identity column id and a label column. See an example that creates its own table.
try (Statement insert = connection.createStatement()) {
insert.executeUpdate("INSERT INTO public.orders (label) VALUES ('First order')",
Statement.RETURN_GENERATED_KEYS);
try (ResultSet keys = insert.getGeneratedKeys()) {
while (keys.next()) {
long orderId = keys.getLong(1);
System.out.println(orderId);
}
}
}
With RETURN_GENERATED_KEYS, getGeneratedKeys() returns an empty result if no identity values were generated, for example when every identity value was supplied explicitly. On a server without this capability, a request to return keys or a call to getGeneratedKeys() raises SQLFeatureNotSupportedException. For one insert, choose either a JDBC generated-key request or SQL INSERT ... RETURNING. See SQL identity columns and prepared generated keys.
On a server with generated-key support, a plain Statement batch collects generated identity values in batch order. Retrieve them with getGeneratedKeys() after the batch. Prepared batches use the key selection specified when the statement was created.
Batch failures
When the server reports a batch failure, executeBatch() and executeLargeBatch() throw BatchUpdateException. Its cause is the original server diagnostic, including any SQLSTATE and vendor code supplied by the server.
The exception’s getUpdateCounts() and getLargeUpdateCounts() return counts for the completed entries the server reports. An explicit report with zero completed entries produces an empty array. Both methods return null if the server provided no progress report. With generated-key support, statement.getGeneratedKeys() can read any keys reported for completed entries.
Progress describes execution. In auto-commit mode, completed entries may already be committed. When auto-commit is disabled, use rollback() if you want to discard work in the current transaction. If no progress was reported, check the outcome before retrying the batch. See JDBC errors.
Example: create a table and insert rows
Run this on a development instance where public.jdbc_docs_tasks does not yet exist. The other JDBC reference examples use these rows.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Arrays;
public class CreateTasks {
public static void main(String[] args) throws Exception {
String url = args.length == 0 ? "jdbc:polypheny://localhost:20590" : args[0];
try (Connection connection = DriverManager.getConnection(url, "pa", "");
Statement statement = connection.createStatement()) {
statement.executeUpdate("CREATE TABLE public.jdbc_docs_tasks "
+ "(id INTEGER PRIMARY KEY, title VARCHAR(100), owner VARCHAR(100))");
statement.addBatch("INSERT INTO public.jdbc_docs_tasks (id, title) VALUES (1, 'Write docs')");
statement.addBatch("INSERT INTO public.jdbc_docs_tasks (id, title) VALUES (2, 'Review docs')");
System.out.println(Arrays.toString(statement.executeBatch()));
if (statement.execute("SELECT id, title FROM public.jdbc_docs_tasks ORDER BY id")) {
try (ResultSet rows = statement.getResultSet()) {
while (rows.next()) {
System.out.printf("%d %s%n", rows.getInt("id"), rows.getString("title"));
}
}
}
}
}
}
Settings and lifecycle
| Method | Behavior |
|---|---|
close(), isClosed() |
Release resources and inspect the statement’s local closed state. |
closeOnCompletion(), isCloseOnCompletion() |
Set or read whether closing the statement’s result also closes the statement. |
getConnection() |
Returns the parent JDBC connection. |
setFetchSize(rows), getFetchSize() |
Set or read the fetch size hint for result frames. The default is 100. Use 0 to use the driver’s default fetch size. Negative values are rejected. |
setFetchDirection(direction), getFetchDirection() |
The supported direction is ResultSet.FETCH_FORWARD. A scrollable cursor can still move backward across fetched rows. |
setMaxFieldSize(bytes), getMaxFieldSize() |
Set or read the local field limit. Strings are truncated by Java string length and binary values by byte length. The default 0 imposes no field size limit. |
setMaxRows(rows), getMaxRows(), setLargeMaxRows(rows), getLargeMaxRows() |
Set or read the number of rows exposed by a result, including a generated-key result. The default 0 has no limit. Set a limit in SQL when the server needs to restrict the rows it produces. |
setQueryTimeout(seconds), getQueryTimeout() |
Set or read the statement’s execution timeout in seconds. 0 disables the query deadline. See query and network timeouts. |
cancel() |
Checks that the statement is open. Use setQueryTimeout to bound execution. |
getResultSetType(), getResultSetConcurrency(), getResultSetHoldability() |
Report the settings chosen at creation. |
setPoolable(poolable), isPoolable() |
Store or read the poolable flag. The driver does not provide statement pooling. |
getWarnings(), clearWarnings() |
The driver does not track warnings. getWarnings() returns null. |
setEscapeProcessing(enabled) |
Stores the flag. The driver sends SQL as supplied without rewriting JDBC escapes. |
setCursorName(name) |
Unsupported. |
isWrapperFor(type), unwrap(type) |
Check or obtain the implementation for a compatible type. |
Query and network timeouts
Use Statement.setQueryTimeout(seconds) to bound a statement execution, including a prepared statement or batch. The query deadline covers waiting to send the request and cleaning up results from the previous execution. If that deadline expires before the request is sent, the call raises SQLTimeoutException and the connection stays open. If a cleanup request was already sent and its response misses the deadline, the connection can close before the new SQL is sent.
On servers that support query cancellation, the driver sends the remaining query budget with the request. The server starts that budget when it first reads bytes of the request. Time in transit before those bytes arrive can add to the total wait. A confirmed cancellation raises SQLTimeoutException and leaves the connection open. The server can roll back the current manual transaction, including earlier uncommitted changes. For a batch, the cause is a BatchUpdateException with any progress the server reported. On older servers, the driver can stop waiting locally while the outcome of an already-sent request remains uncertain.
Connection.setNetworkTimeout(executor, milliseconds) sets a separate network deadline. An expired deadline on an outstanding request can close the connection even while the server is still enforcing its query budget. Interrupted or incomplete sends can also close the connection. For an unconfirmed execution, check what the server committed before retrying. See connection settings.