PreparedStatement
A PreparedStatement is a SQL template with ? placeholders. You bind values with setString, setInt, and the rest. The driver sends data separately from SQL, which stops injection and can reuse a plan.
Detailed Explanation
Statement.execute("select * from users where id = " + id) is how injection and type bugs start. prepareStatement("select * from users where id = ?") plus setLong(1, id) keeps the value out of the SQL text. The database sees a parameter.
Indexes are 1-based. That surprises everyone. setObject exists; prefer the typed setters. null needs setNull(index, Types.INTEGER) or setObject(index, null). A leftover bind from a previous loop iteration is a classic batch bug; always set every parameter each time.
The driver or the database may cache the plan. In PostgreSQL the first executions can be unprepared until a threshold; that is still safer than concat. PreparedStatement is per connection. Do not share it across threads.
You reach for prepared statements for every statement that includes data. You keep a Statement only for fixed SQL with no user values (select 1). Batch addBatch / executeBatch on a prepared statement is how you insert many rows without a round trip per row.
The cost of building a new prepared statement per call is parse overhead; a pool of connections still prepares often, which is fine. The cost of string-built IN lists (in ( + ids + )) is injection if ids are not integers you trust. Use a list of ? or a vendor array type.
CallableStatement extends this for stored procedures. Named parameters are not in core JDBC; some drivers add them.
When you generate a list of placeholders for an IN clause, build it from the size of a trusted collection of binds, not from user text. "?" + ",?".repeat(ids.size()-1) plus a loop of setLong is fine. Pasting the ids into the string is not. Some databases cap the number of parameters; then you chunk the list. That chunking is still bound data. It is not an excuse to concat.
Code Examples
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Find {
static String name(Connection c, long id) throws Exception {
try (PreparedStatement ps = c.prepareStatement("select name from users where id = ?")) {
ps.setLong(1, id); // first placeholder is 1
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? rs.getString(1) : null;
}
}
}
}import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Types;
public class MaybeAge {
static void update(Connection c, long id, Integer age) throws Exception {
try (PreparedStatement ps = c.prepareStatement("update users set age = ? where id = ?")) {
if (age == null) {
ps.setNull(1, Types.INTEGER);
} else {
ps.setInt(1, age);
}
ps.setLong(2, id);
ps.executeUpdate();
}
}
}Common Gotchas
Placeholders are 1-based
`setLong(0, id)` throws.
Building `IN (?)` with one placeholder for a list does not expand
generate N marks or use an array.