JDBC Driver - Prepared Statement

A java.sql.PreparedStatement prepares SQL with positional ? markers. Bind values with setters before executing the command. The first parameter index is 1. Bind application values separately from SQL text. SQL identifiers such as table names are part of the SQL statement.

Execute and batch

Method Behavior
executeQuery() Executes the bound statement and returns a relational ResultSet.
executeUpdate(), executeLargeUpdate() Execute a statement that returns an update count. Choose the long form for large counts.
execute() Executes and returns true for a result set. Use getResultSet() or getUpdateCount() as for a Statement.
clearParameters() Clears the current bindings. Individual executions retain their bindings until you replace or clear them.
addBatch() Adds a snapshot of current bindings to the prepared batch. Bind each row before adding it.
executeBatch(), executeLargeBatch() Execute the prepared batch and return counts in batch order as int[] or long[]. When the server returns only a combined count for multiple entries, the driver returns Statement.SUCCESS_NO_INFO for each one. Batch execution clears queued parameter sets. See batch failures.
clearBatch() Clears parameter sets queued with addBatch().
getMetaData() Returns null. To inspect query output, call getMetaData() on the resulting ResultSet.
getParameterMetaData() Returns parameter metadata from the server’s statement signature.

Use the overloads without a SQL string. The inherited SQL-string execution and batch methods do not provide a supported way to execute new SQL with a prepared statement.

Generated keys

Select generated keys when you prepare the SQL. Use connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS) for generated identity values, or supply a String[] of column names or an int[] of one-based target column positions. Execute with the no-argument methods and read the keys with getGeneratedKeys() before reusing the statement or committing the transaction.

This example requests two columns in the order id, label from an existing public.orders table with an identity column id.

try (PreparedStatement insert = connection.prepareStatement(
        "INSERT INTO public.orders (label) VALUES (?)", new String[] {"id", "label"})) {
    insert.setString(1, "First order");
    insert.executeUpdate();
    try (ResultSet keys = insert.getGeneratedKeys()) {
        while (keys.next()) {
            System.out.printf("%d %s%n", keys.getLong(1), keys.getString(2));
        }
    }
}

In a prepared batch, each addBatch() keeps a snapshot of the current bindings. The generated-key selection applies to every entry. After executeBatch() or executeLargeBatch(), read all returned rows from a single getGeneratedKeys() result. Check server support before preparing a statement with a key request. See generated-key support and batch failures.

Example: bind query parameters

First run the Statement setup example.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class FindTask {
    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", "");
             PreparedStatement query = connection.prepareStatement(
                 "SELECT title FROM public.jdbc_docs_tasks WHERE id = ?")) {
            System.out.println("Parameters: " + query.getParameterMetaData().getParameterCount());
            query.setInt(1, 1);
            try (ResultSet result = query.executeQuery()) {
                if (result.next()) {
                    System.out.println(result.getString("title"));
                }
            }
        }
    }
}

Setter methods for value

Values Setters and behavior
Null setNull(index, sqlType) and setNull(index, sqlType, typeName) both bind an untyped Prism null.
Booleans and numbers setBoolean, setByte, setShort, setInt, setLong, setFloat, setDouble and setBigDecimal.
Text and binary setString, setNString and setBytes.
Date and time setDate, setTime and setTimestamp with or without a Calendar.
Streams and readers setCharacterStream and setNCharacterStream honor a supplied character length. The length overloads for setAsciiStream and setBinaryStream read the full stream. setUnicodeStream is deprecated.
LOBs and arrays setBlob, setClob, setNClob and setArray. Stream and reader LOB bindings can materialize the input in memory, and the length overloads do not limit how much data is read.
Object conversion setObject(index, value) infers a supported Prism value from the Java type. setObject(index, value, targetSqlType) uses a supported java.sql.Types integer target. The scale-or-length overload and the JDBC default SQLType overloads are unsupported. Prefer specific setters for predictable conversions.
Unsupported bindings setRef, setURL, setRowId, setSQLXML and SQL Struct binding.
© Polypheny GmbH. All Rights Reserved.