Data access with JDBC
JDBC (Java Database Connectivity) is the standard low-level API through which Java code talks to a relational database. Everything is built around three things: a Connection (the link to the database), a Statement/PreparedStatement (the query), and a ResultSet (a cursor over the returned rows). ORMs like Hibernate and Spring Data are layers on top that ultimately issue the same JDBC calls.
Nearly the whole point of the topic reduces to one interview question: how does Statement differ from PreparedStatement, and why is the latter the default choice. The answer ties two things together at once — security (SQL-injection safety) and performance (precompilation and plan reuse). The breakdown is in the layer below.
Topic map
- Statement and PreparedStatement —
Statementsends the whole string,PreparedStatementsends a template with bound parameters; why that closes injection and speeds up repeated queries.
Common traps
| Mistake | Consequence |
|---|---|
| Building SQL by concatenating user input | An open SQL injection: input ' OR '1'='1 returns every row in the table |
| Treating manual quote-escaping as a substitute for binding | Escaping is fragile and bypassable; only parameter binding is reliable |
| Confusing which one is parameterized | PreparedStatement is parameterized and safe, Statement is not |
| Assuming the performance is identical | PreparedStatement compiles the plan once and reuses it |
Not closing ResultSet/Statement/Connection | Leaked resources and connections — use try-with-resources |
Interview relevance
JDBC is rarely probed deeply, but Statement vs PreparedStatement is an almost mandatory junior/mid question: it tests SQL-injection understanding from both sides — how injections are created and how they are closed.
Typical checks:
- The difference between sending a full SQL string and a parameterized template.
- Why a bound parameter cannot be interpreted as part of the SQL syntax.
- Why manual escaping is not a substitute for parameter binding.
- What precompilation buys you and when reusing one
PreparedStatementpays off.
Common wrong answer: "PreparedStatement just escapes quotes for you." No — the value never enters the query text at all: the database first compiles the template with placeholders, and the data is supplied on a separate channel as typed parameters, so the SQL parser never sees it.