JDBC interview questions and answers for Java developers
JDBC interview questions check whether you can talk to a relational database from Java safely and efficiently: getting connections from a pool, using PreparedStatement against SQL injection, managing transactions by hand, batching writes and always releasing resources. Expect definitions for freshers, code to write or review for mid-level roles, and production scenarios such as an exhausted pool or a slow bulk load for senior ones. Even teams that use JPA expect you to know what happens underneath.
By Evin JohnPublished 8 min read
Why interviewers still ask about JDBC
Most Java services reach the database through Spring Data, Hibernate or a query builder, but every one of those sits on JDBC. When a pool runs dry at peak, a batch job takes hours or a transaction commits half its work, the fix lives at this layer. That is why JDBC appears in Java developer screens, in backend loops at banks and enterprises, and in data engineering roles that move rows between systems. The ORM layer is covered in JPA interview questions and Hibernate interview questions.
- Concept questionsWhat JDBC is, driver types, the core interfaces and the order of calls to run a query.
- Write or review DAO codeA method that queries or updates with PreparedStatement, closes everything and handles errors.
- TransactionsGroup two updates atomically, explain auto-commit and choose an isolation level.
- Production scenariosConnection leaks, pool timeouts, slow inserts and long-running reports.
JDBC fundamentals questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is JDBC? | Basics | The standard Java API in java.sql and javax.sql for connecting to relational databases, sending SQL and reading results. Each database vendor ships a driver that implements it. |
| What are the four driver types? | History | Type 1 bridged to ODBC (removed from the JDK long ago), type 2 called native client libraries, type 3 talked to middleware, type 4 is pure Java speaking the database's wire protocol. Almost every modern driver is type 4. |
| Do you still need Class.forName to load a driver? | Modern JDBC | No. Since JDBC 4.0, drivers on the classpath register themselves through the service loader mechanism. Old tutorials still show the call. |
| What are the steps to run a query? | API flow | Get a Connection, create a PreparedStatement, bind parameters, execute, iterate the ResultSet, then close the result set, statement and connection, ideally with try-with-resources. |
| Statement, PreparedStatement or CallableStatement? | Statement types | Statement runs fixed SQL text. PreparedStatement takes parameters and can be precompiled and reused. CallableStatement calls stored procedures and reads OUT parameters. |
| execute, executeQuery or executeUpdate? | Execution | executeQuery returns a ResultSet for a SELECT. executeUpdate returns an affected row count for DML or zero for DDL. execute returns a boolean and suits SQL whose result type you do not know. |
| Are ResultSet column indexes zero-based? | Detail | No, they start at 1, as do parameter indexes in a PreparedStatement. |
| How do you read a nullable integer column? | NULL handling | getInt returns 0 for SQL NULL, so call wasNull afterwards, or use getObject(col, Integer.class) to get null directly. |
| What is ResultSetMetaData for? | Metadata | Column count, names and types of a result, which generic tools such as exporters use. DatabaseMetaData describes the database itself: tables, keys and supported features. |
| How do you read dates in modern JDBC? | Types | With getObject(col, LocalDate.class) or OffsetDateTime and setObject for parameters, avoiding the old java.sql.Date and Timestamp classes and their time zone surprises. |
Intermediate questions: safety, transactions and batching
import java.sql.*;
import javax.sql.DataSource;
public class TransferDao {
private final DataSource pool;
public TransferDao(DataSource pool) { this.pool = pool; }
/** Moves money between two accounts in one transaction. Amounts are in minor units. */
public void transfer(long fromId, long toId, long amount) throws SQLException {
String debit = "UPDATE account SET balance = balance - ? WHERE id = ? AND balance >= ?";
String credit = "UPDATE account SET balance = balance + ? WHERE id = ?";
try (Connection con = pool.getConnection()) {
con.setAutoCommit(false);
try (PreparedStatement d = con.prepareStatement(debit);
PreparedStatement c = con.prepareStatement(credit)) {
d.setLong(1, amount); d.setLong(2, fromId); d.setLong(3, amount);
if (d.executeUpdate() != 1) throw new SQLException("insufficient funds or no account " + fromId);
c.setLong(1, amount); c.setLong(2, toId);
if (c.executeUpdate() != 1) throw new SQLException("no account " + toId);
con.commit();
} catch (SQLException e) {
con.rollback();
throw e;
} finally {
con.setAutoCommit(true); // the pool hands this connection to someone else next
}
}
}
/** Inserts many rows with one round trip per batch instead of one per row. */
public int[] insertEvents(long accountId, String[] types) throws SQLException {
String sql = "INSERT INTO event (account_id, type) VALUES (?, ?)";
try (Connection con = pool.getConnection();
PreparedStatement ps = con.prepareStatement(sql)) {
for (String type : types) {
ps.setLong(1, accountId);
ps.setString(2, type);
ps.addBatch();
}
return ps.executeBatch();
}
}
}- How does PreparedStatement stop SQL injection? Parameter values travel separately from the SQL text, so the database never parses user input as SQL. Concatenating input into the string reopens the hole even inside a PreparedStatement.
- Can you bind a table name or a sort column as a parameter? No, placeholders only stand for values. Pick identifiers from an allowlist in code, never from raw input.
- How do you pass a variable-length IN list? Generate the right number of placeholders and bind each value, use a database array type where the driver supports it, or load the values into a temporary table for very long lists.
- What does auto-commit mean? By default each statement commits on its own. Turning it off groups statements into one transaction that you end with commit or rollback.
- Why reset auto-commit in the transfer code? A pooled connection is reused by the next caller. Leaving it in manual mode, or with an uncommitted transaction, leaks state into unrelated work. Many pools reset this for you, but do not count on it in an interview answer.
- What is a savepoint? A marker inside a transaction you can roll back to without abandoning the whole transaction, useful when one optional step may fail.
- Which isolation levels does JDBC expose? READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ and SERIALIZABLE through setTransactionIsolation. Each database supports and implements them differently, so know your engine's default and what anomaly each level allows.
- Why batch inserts? One network round trip per row dominates the cost of bulk writes. addBatch and executeBatch send rows in groups; some drivers need a connection property to rewrite batches into multi-row statements, so check the driver documentation.
- How do you get the ID the database generated? Prepare the statement with
Statement.RETURN_GENERATED_KEYSor a column name array, execute, then read getGeneratedKeys. - What does setFetchSize do? Hints how many rows the driver pulls per round trip. Large reports need it to stream instead of loading everything into memory, and some drivers only stream inside a transaction or with specific settings.
- What happens when one statement in a batch fails? executeBatch throws BatchUpdateException, whose update counts show which statements ran. Whether the rest continue depends on the driver, so wrap the batch in a transaction if it must be all-or-nothing.
Connection pools and resource management
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Why use a DataSource and a pool instead of DriverManager? | Architecture | Opening a physical connection means a network handshake and authentication. A pool keeps connections open and lends them out; a DataSource lets the container or framework configure that, and close returns the connection to the pool. |
| Which pool have you used? | Practice | HikariCP is the default in Spring Boot; others include Apache DBCP and the pools built into application servers. Name the settings you tuned: maximum size, connection timeout, idle timeout and max lifetime. |
| How big should a pool be? | Sizing | Smaller than most people guess. The database can only run so many queries at once, so a modest pool with short transactions usually beats a huge one. Size from measurement, and remember every app instance multiplies the total. |
| What does try-with-resources guarantee? | Cleanup | Resources declared in it close in reverse order even when an exception is thrown, and suppressed exceptions stay attached to the main one. |
| What is a connection leak and how do you find it? | Debugging | A borrowed connection never closed, often on an exception path. Symptoms: pool timeouts that grow over hours. Pools can log a stack trace for connections held too long, which points at the leaking code. |
| What information does SQLException carry? | Errors | A message, the vendor error code, the SQLState (a standard class such as 23 for integrity violations) and a chain of next exceptions. Subclasses mark transient and integrity cases. |
| How do you stop a query that runs forever? | Timeouts | setQueryTimeout on the statement, a statement timeout configured in the database, and a pool connection timeout so callers fail fast instead of piling up. |
| What is a RowSet? | Less common API | A ResultSet that is also a JavaBean. CachedRowSet works disconnected, which was handy for passing data between tiers; it is rarely used in new code. |
Senior and scenario questions
- At peak, requests fail with "connection is not available, request timed out". How do you investigate? Check pool metrics for active, idle and waiting counts, look for slow queries holding connections, long transactions wrapping remote calls, and leaks. Raising the pool size is the last step, since it often just moves the queue into the database.
- A nightly load of five million rows takes hours. What do you change? Batch with a sensible size, commit every few batches rather than per row or once at the end, turn on the driver's batch rewriting if it has one, drop or defer secondary indexes where safe, or use the database's bulk loader such as COPY.
- When would you use plain JDBC or JdbcTemplate instead of JPA? Bulk updates, reporting queries with complex joins, database-specific features and hot paths where you want exact SQL. Keep JPA for ordinary entity work and mix carefully inside one transaction.
- What does Spring's JdbcTemplate add? It handles getting and releasing connections, closes statements and result sets, and translates SQLException into a DataAccessException hierarchy that is independent of the vendor.
- How do you test DAO code? Against a real database of the same engine, for example in a container per test run, with each test in a rolled-back transaction or a fresh schema. In-memory substitutes can hide dialect differences.
- How would you read a huge table without running out of memory? A forward-only, read-only result set with a fetch size, processing rows as they stream, or keyset pagination in chunks so each query is short.
- Two services update the same row. How do you prevent lost updates in plain JDBC? Add a version column and include it in the WHERE clause, checking the update count; or lock the row with SELECT ... FOR UPDATE inside a short transaction.
- How do you make credentials safe? Load them from a secret store or environment, never from source, give the account only the privileges the service needs, and use TLS to the database.
Fictional example
- Interviewer
- This method builds a SELECT by concatenating the user's search term, opens a connection with DriverManager, and returns a list. What would you change?
- Candidate
- Three things first. Security: the concatenation is an injection hole, so I would switch to a PreparedStatement with a placeholder for the term, and if the term feeds a LIKE, escape the wildcard characters too. Resources: nothing is closed if the loop throws, so I would wrap the connection, statement and result set in try-with-resources. Connections: DriverManager opens a fresh physical connection on every call, so I would inject a pooled DataSource. Then I would look at the query itself, add a LIMIT and an ordered key for paging, and check the plan to see whether the search can use an index at all.
JDBC practice plan
- Day 1: write a small DAO against a local database you already use, with a query, an insert returning its generated key and a NULL column read correctly.
- Day 2: implement the transfer method from memory, then break it on purpose (fail the second update) and confirm the rollback.
- Day 3: insert fifty thousand rows one by one, then in batches, and compare the time. Try the driver's batch rewrite setting if it has one.
- Day 4: add a pool, shrink it to two connections, leak one on purpose and read what the pool reports.
- Day 5: rehearse the scenario questions aloud, ending each answer with what you would measure.
Related reading: SQL interview questions for the queries you send through JDBC, Spring Boot interview questions for how Boot wires the DataSource and transactions, and JSP interview questions for older Java web apps that still call JDBC from servlets. If your role also touches mainframe batch, JCL interview questions covers how those jobs are defined.
Code review answers depend on covering the issues in a sensible order, security before style. Natively, an AI interview assistant for Mac and Windows, transcribes your mock backend round on the computer, so you can see afterwards whether you caught the injection, the leak and the pool question. In practice it can read a DAO method from a screenshot and suggest points to raise, and with Pro or the free trial it takes your résumé and the job description into account. You keep the transcript and notes for review.
Questions people ask
What JDBC questions are asked in Java interviews?
Driver types, DriverManager versus DataSource, Statement versus PreparedStatement versus CallableStatement, SQL injection, auto-commit and transactions, isolation levels, batch updates, connection pooling and closing resources.
Why use PreparedStatement instead of Statement?
Parameters are sent separately from the SQL text, which prevents SQL injection, and the statement can be reused and often precompiled by the database.
How do you manage a transaction in JDBC?
Call setAutoCommit(false), run the statements, then commit, or roll back in the catch block. Restore auto-commit before returning a pooled connection.
Why use a connection pool?
Opening a physical database connection is slow. A pool keeps connections open and lends them out, and closing a pooled connection returns it instead of closing the socket.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
