JDBC connection and prepared statements
What you will learn
JDBC is a Java API for talking to a relational database through a driver. A DataSource supplies a connection; a prepared statement binds data values separately from SQL text.
- Explain connection ownership and driver requirements.
- Bind typed values without concatenating user input.
- Choose query or update methods and restrict dynamic identifiers.
Prerequisite: Java exceptions, interfaces, Optional and testing fundamentals. Database execution is NOT RUN; local JDK-only examples and test doubles are checked separately.
Find stock with a bound parameter
import java.sql.*;import javax.sql.DataSource;import java.util.OptionalInt;
public class Lookup { static OptionalInt stock(DataSource source, String sku) throws SQLException { try (Connection c = source.getConnection(); PreparedStatement p = c.prepareStatement( "SELECT stock FROM catalog_item WHERE sku = ?")) { p.setString(1, sku); try (ResultSet r = p.executeQuery()) { return r.next() ? OptionalInt.of(r.getInt("stock")) : OptionalInt.empty(); } } }}Compiled with JDK only; database call NOT RUN. With a configured disposable database, a row with stock 5 returns OptionalInt.of(5); absent SKU returns empty. The schema disallows NULL stock.
The boundary
The java.sql and javax.sql packages are part of Java SE, but a database-specific driver and configured database are separate requirements. DriverManager selects a registered driver from a JDBC URL; a DataSource abstracts connection acquisition and can be injected into a repository. A DataSource is not necessarily a pool. A pooled connection close usually returns a logical connection to its manager; follow that manager’s reset and failure policy. Do not embed credentials or connect to a real service in this lesson.
Prepare and bind
A question mark denotes a value parameter in this SQL context, not a table or column name. Bind positions from one, use types compatible with column types, and set every parameter before execution. Use executeQuery for a single result set and executeUpdate for a row count (or zero for statements with no count). Parameterization protects the SQL structure when used correctly; it does not enforce business permissions. For optional ordering choose among fixed trusted SQL identifiers, not arbitrary supplied text.
Ownership and batch
The caller owns the borrowed connection, then the statement, then its result. Nested try-with-resources releases them in reverse acquisition order. Do not return an open ResultSet from a method that closes its statement. addBatch records parameter sets and executeBatch returns per-command outcomes; inspect counts and SUCCESS_NO_INFO or EXECUTE_FAILED and BatchUpdateException. A batch alone is not an all-or-nothing transaction.
Choose a trusted sort identifier
public class Main { static String ordering(String key) { return switch (key) { case "sku" -> "sku"; case "stock" -> "stock"; default -> throw new IllegalArgumentException("unknown ordering"); }; } public static void main(String[] args) { System.out.println("SELECT sku, stock FROM catalog_item ORDER BY " + ordering("stock")); try { ordering("other"); } catch (IllegalArgumentException e) { System.out.println("rejected"); } }}Locally executed: prints the fixed ORDER BY stock SQL, then rejected. This tests the allowlist only, not database execution.
Batch repeated inserts
import java.sql.*;import java.util.List;
public class Batch { // Caller owns the connection and transaction; commit only after checking results. static int[] add(Connection c, List<String> skus) throws SQLException { try (PreparedStatement p = c.prepareStatement( "INSERT INTO catalog_item(sku, stock) VALUES (?, ?)")) { for (String sku : skus) { p.setString(1, sku); p.setInt(2, 0); p.addBatch(); } return p.executeBatch(); } }}Compiled, database NOT RUN. Caller must disable auto-commit, check returned counts and decide commit or rollback; duplicate behavior depends on driver/database.
Common mistakes
Do not concatenate input into SQL, bind identifiers as if they were values, assume every DataSource pools, or reuse a result after its owner closes.
Practice
Design a search for a SKU containing an apostrophe with sort choices sku or stock. Show the fixed SQL, binding call and rejection of an unknown sort key.
Use the manual practice hints; explain your reasoning before consulting the private review solution.
Official reading: datasource · prepared · connection.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JDBC connection and prepared statements — knowledge check
JDBC knowledge check.
What supplies a JDBC connection?
What index binds the first value?
Can a placeholder select a table name?
Which call returns a result set for a SELECT?
Does executeBatch guarantee atomicity?