If you’re preparing for a Java developer role, chances are that JDBC will come up in the interview. You probably even saw it mentioned in the job description and are wondering how to prepare for it. That is what this guide is for; we have collated the most commonly asked JDBC interview questions, ranging from fundamentals to advanced. All laid out in perfect order to help you brush up quickly and maybe even learn a few new topics. Let’s begin.
Table of Content:
JDBC Interview Questions for Freshers (Fundamentals)
Every strong interview starts with the basics, and that is where we shall begin as well. Here is a list of JDBC interview questions aimed at freshers and newbies. They will get you started on the road and even help you build some confidence.
1. What is JDBC?
Imagine that you are building a Java application, and you need to pull data from a database for some reason. Usually, you would have to write queries in the language that the database uses, such as MySQL, Oracle, PostgreSQL, etc. JDBC (Java Database Connectivity) is an API that allows you to overcome this. It acts as a translator between your application and the database. You can write your database code in Java, and JDBC will translate it into commands that the database will understand. Using JDBC, you can send queries, fetch results, and manage data in a standardized manner.
2. What are the benefits of using JDBC?
Switching databases has always been a headache for developers. Each time you do, you will have to rewrite the database layer of your code, which can be difficult, especially for large projects. JDBC solves this problem and gives you the advantage of:
- Portability: Your code isn’t database-specific.
- Convenience: JDBC handles connection setup, sending queries, and parsing results.
- Flexibility: Works with nearly all relational databases.
3. What are the core components of the JDBC API?
The JDBC API is powered by a few VIP classes and interfaces:
- DriverManager: The gatekeeper that picks the right driver for the right job.
- Connection: Represents a live session with the database.
- Statement/PreparedStatement/CallableStatement: These are the tools that you can use to send SQL commands.
- ResultSet: Holds the data returned from a query.
4. Explain the different types of JDBC drivers.
JDBC has four types of drivers. You can think of them as different generations of “adapters”.
Type |
Driver Name |
Key Points |
Type 1 |
JDBC-ODBC Bridge |
This is the old-school driver that converts JDBC calls into ODBC calls. It’s slow and considered outdated, so it’s best avoided in modern applications. |
Type 2 |
Native-API Driver |
This driver relies on the database’s native libraries, like Oracle OCI. It’s faster than Type 1 but isn’t portable across different databases. |
Type 3 |
Network Protocol Driver |
Here, a middle-tier server translates JDBC calls into database-specific commands. It’s flexible and can work with multiple databases, but you’ll need extra setup. |
Type 4 |
Thin / Pure Java Driver |
This driver talks directly to the database using its protocol. Being 100% Java, it’s portable and widely preferred in most modern applications. |
5. Which is the most commonly used JDBC driver?
Type 4 (Pure Java) is the fastest and most popular driver as it removes all the extra layers, works across platforms, and does not require native client libraries.
6. What is DriverManager in JDBC?
You can think of DriverManager as the central manager of all JDBC drivers. When your application makes a request for a database connection, DriverManager scans the registered drivers and selects the one that matches your database URL.
7. What is DataSource in JDBC?
DataSource is the modern, enterprise-friendly alternative to DriverManager.
- DriverManager: Used for small standalone applications.
- DataSource: Best for larger systems due to its support of connection pooling, distributed transactions, and easier configuration.
8. What is Statement in JDBC?
A Statement is the simplest way to execute SQL queries in JDBC. This is how you can create a connection and use it to send SQL commands:
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
9. Explain the different types of statements in JDBC.
There are three types of statements in JDBC:
- Statement: Executes static SQL queries.
- PreparedStatement: Think of this as a query template. You write the SQL once using placeholders and fill in the values at runtime. It’s faster, safer, and helps prevent SQL injection.
- CallableStatement: Used for calling stored procedures in the database. It’s useful when you want to keep the complex login within the database and not your Java code.
10. What is PreparedStatement? Why is it preferred over Statement?
A PreparedStatement is like a query template where you plug in values at runtime. It’s preferred because:
- Faster execution: The SQL is precompiled by the database, so it runs more efficiently.
- Safer: Prevents the risk of SQL injection.
- Easier to manage: Handling parameters becomes straightforward, especially when you have multiple values to insert or update.
11. What is CallableStatement?
In JDBC, a CallableStatement is used when you want to call a stored procedure in your database. Stored procedures are pre-written SQL queries that allow you to perform complex actions such as updates, calculations, or data retrievals. Here is how you can do it:
CallableStatement cs = conn.prepareCall("{call getUserById(?)}");
cs.setInt(1, 101);
ResultSet rs = cs.executeQuery();
12. What is ResultSet?
The ResultSet interface is used to represent the result of the execution of SQL queries using statement objects. And the types include:
Type |
Description |
Key Points |
Forward-only |
Default type |
Moves only forward; you can’t go back once you’ve moved past a row. |
Scroll-insensitive |
Can scroll both ways |
Lets you scroll back and forth, but doesn’t show changes made in the database after the query ran. |
Scroll-sensitive |
Can scroll both ways |
You can scroll both ways, and it reflects real-time updates in the database. |
Updatable |
Can modify data |
Allows you to update, insert, or delete rows directly through the ResultSet. |
13. What is RowSet? Explain its different types.
Think of RowSet as ResultSet on steroids. It’s scrollable, updatable, and even works offline. These are the different types:
RowSet Type |
Key Features |
JdbcRowSet |
A connected RowSet that extends ResultSet. It’s scrollable and updatable, making it simple to work with live data. |
CachedRowSet |
A disconnected RowSet that doesn’t need a constant database connection, ideal for lightweight or offline operations. |
WebRowSet |
Builds on CachedRowSet and can read/write XML, making it perfect for web applications. |
FilteredRowSet |
Extends CachedRowSet and allows filtering rows using custom predicates. |
JoinRowSet |
Lets you combine multiple RowSets into one logical view, supporting database-style joins in memory. |
14. Can you get a null ResultSet in JDBC?
No, the ResultSet object is never null. If the query doesn’t return any rows, the ResultSet is simply empty.
15. What is the difference between ResultSet and RowSet?
Feature |
ResultSet |
RowSet |
Connection |
Always connected to the database |
Can be disconnected, making it more flexible |
Scrolling |
Forward-only by default |
Scrollable both forwards and backwards |
Features |
Basic functionality, less flexible |
Offers richer features like filtering, joining, and XML support |
Use case |
Ideal for simple queries |
Great for flexible, portable solutions, especially in web applications |
16. Explain ResultSetMetaData and DatabaseMetaData.
Metadata in JDBC provides essential information about either your SQL query or the database itself. There are two main types of metadata in JDBC:
MetaData |
Key Points |
ResultSetMetaData |
Shows the structure of query results – column names, types, and count. |
DatabaseMetaData |
Provides information about the database – tables, supported features, drivers, and capabilities. |
17. How do Java applications access the database using JDBC? Explain with steps.
Steps to connect Java with a database using JDBC:
- Load the driver class (Class.forName(“com.mysql.cj.jdbc.Driver”)).
- Establish a connection using DriverManager or DataSource.
- Create a Statement/PreparedStatement.
- Execute the SQL query.
- Process the results with ResultSet.
- Close the resources.
JDBC Interview Questions for Executing Queries and Handling Data
Once you know how to connect to a database, the real test is what you can do with that connection. Interviewers expect you to not only be able to run queries but also process the results effectively. These JDBC interview questions are designed to teach you just that.
18. Explain the difference between executeQuery(), executeUpdate(), and execute().
Method |
Used For |
Returns |
Key Point |
executeQuery() |
SELECT statements |
A ResultSet with the retrieved data |
Best for reading data without making changes |
executeUpdate() |
INSERT, UPDATE, DELETE |
An int showing how many rows were affected |
Best for modifying data |
execute() |
Any SQL command |
true if it returns a ResultSet, false if it’s an update count |
Use when you’re unsure if the SQL returns data or just updates |
2. How do you iterate through a ResultSet and retrieve data?
A ResultSet in JDBC acts like a cursor that points to the rows returned by the query. By default, it starts before the first row, and you can move it forward one row at a time using rs.next().
Inside the loop, you can grab the column values using the appropriate getter methods. Each call will fetch the value of the current row.
For example:
ResultSet rs = stmt.executeQuery("SELECT id, name FROM users");
while (rs.next()) {
int id=rs.getInt("id");
String name = rs.getString("name");
System.out.println(id + " - " + name);
}
19. What are getter and setter methods in ResultSet?
Method Type |
What It Does |
When to Use |
Examples |
Getter methods |
Fetch data from the current row of a ResultSet |
When you want to read/query values after running a SELECT statement. |
getInt(), getString(), getDate() |
Setter methods |
Change values in the current row, and optionally write them back to the database |
When you want to update or insert data directly through the ResultSet instead of writing a separate SQL statement. |
updateInt(), updateString(), updateRow() |
20. What is the use of getGeneratedKeys() method in JDBC?
When you insert a row into a table with an auto-increment column, the database generates that value automatically. The getGeneratedKeys() method allows you to retrieve those autogenerated values right after the insert.
Example:
PreparedStatement ps = conn.prepareStatement(
"INSERT INTO users(name, email) VALUES(?, ?)",
Statement.RETURN_GENERATED_KEYS
);
ps.setString(1, "Intellipaat");
ps.setString(2, "[email protected]");
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
if (rs.next()) {
int newId = rs.getInt(1);
System.out.println("New user ID: " + newId);
}
Here, the database generates the user’s ID, and getGeneratedKeys() gives you access to it immediately.
21. What are CLOB and BLOB datatypes in JDBC? How do you handle images and files?
- CLOB (Character Large Object): Used for storing large text data (like articles, XML).
- BLOB (Binary Large Object): Used for storing binary data such as images, audio, or video.
To handle them, you typically use streams: setCharacterStream() or setBinaryStream() when inserting, and getCharacterStream() or getBinaryStream() when reading.
22. How to insert an image or raw data into a database table using JDBC?
To insert an image or raw data into a database using JDBC, you can read the file as a stream and set it in the PreparedStatement. For example:
File file = new File("image.jpg");
FileInputStream fis = new FileInputStream(file);
PreparedStatement ps = conn.prepareStatement("INSERT INTO photos(name, data) VALUES(?, ?)");
ps.setString(1, "MyImage");
ps.setBinaryStream(2, fis, (int) file.length());
ps.executeUpdate();
fis.close();
23. How can I manage special characters in an INSERT query?
Special characters like quotes, backslashes, or newlines can break SQL statements. Using PreparedStatement solves this because it automatically escapes dangerous characters:
PreparedStatement ps = conn.prepareStatement("INSERT INTO users(name, comment) VALUES(?, ?)");
ps.setString(1, "Intellipaat");
ps.setString(2, "Hello, I'm learning JDBC!");
ps.executeUpdate();
24. What is batch processing in JDBC? What are its advantages?
Batch processing in JDBC allows you to execute multiple SQL statements rather than individually. The advantages of using batch processing are:
- Reduce round-trip to the database.
- Improved performance when updating or inserting large datasets.
- Makes code cleaner and easier to debug.
25. How to perform batch processing in JDBC?
You can add multiple statements to a batch by using addBatch() and execute them all at once using executeBatch(). Here is an example:
Statement stmt = conn.createStatement();
stmt.addBatch("INSERT INTO students(name) VALUES('Alice')");
stmt.addBatch("INSERT INTO students(name) VALUES('Bob')");
int[] results = stmt.executeBatch();
JDBC Transactions and Connection Management Interview Questions
Maintaining data integrity is the main purpose of JDBC. Interviewers expect this skill above all else, as fixing a broken database can be a costly and time-consuming task. Here, you’ll learn about commits, rollbacks, isolation levels, and savepoints.
26. What is setAutoCommit()? What does setAutoCommit(false) do?
By default, every SQL statement in JDBC runs on its own transaction and is committed as soon as it finishes. setAutoCommit() is what controls this behaviour.
- setAutoCommit(true) (default): Each statement is immediately committed.
- setAutoCommit(false): Turns off auto-commit, allowing you to group multiple statements into a single transaction. You must explicitly call commit() or rollback().
This gives you control over when changes should be finalized.
27. What is JDBC Transaction Management? Why is it important?
Transaction management ensures that a group of SQL operations is executed as a single logical unit. If any one of the steps fails, the entire transaction can be rolled back, maintaining data consistency.
It follows the ACID principles:
- Atomicity: All or nothing.
- Consistency: Data remains valid before and after a transaction.
- Isolation: Transactions don’t interfere with each other.
- Durability: Once committed, changes are permanent.
Without transaction management, partial updates and data corruption can easily occur.
28. How to rollback a JDBC transaction?
If autoCommit() is disabled, you can undo changes using rollback().
try {
conn.setAutoCommit(false);
// execute multiple updates
conn.commit();
} catch (Exception e) {
conn.rollback(); // undo all changes in this transaction
}
29. What is Savepoint in JDBC? How to use it?
A SavePoint allows you to roll back only part of a transaction rather than the entire thing. You can mark a point in the transaction, which you can then return to if you ever need to, instead of rolling back the entire transaction.
conn.setAutoCommit(false);
Savepoint sp1 = conn.setSavepoint("Point1");
try {
// some SQL operations
conn.rollback(sp1); // rollback only to Point1
conn.commit();
} catch(Exception e) {
conn.rollback();
}
This is useful in long and complex transactions.
30. What are the different isolation levels in JDBC?
Isolation levels decide how visible the changes of one transaction are to others.
Isolation Level |
What It Prevents |
Still Possible |
Notes |
READ UNCOMMITTED |
Nothing (least strict) |
Dirty reads, non-repeatable reads, phantom reads |
Fastest but least reliable |
READ COMMITTED |
Dirty reads |
Non-repeatable reads, phantom reads |
Most common default in many databases |
REPEATABLE READ |
Dirty reads, non-repeatable reads |
Phantom reads |
Good balance between consistency and performance |
SERIALIZABLE |
Dirty reads, non-repeatable reads, phantom reads |
None |
Most consistent, but slowest due to strict locking |
31. What is a dirty read? Which isolation level prevents dirty reads?
A dirty read is when one transaction reads the data that another transaction has modified but not yet commited. If the second transaction rolls back, the first transaction ends up working with invalid data.
Prevention: Use READ COMMITTED or higher isolation.
32. What is a phantom read, and how to prevent it?
A phantom read happens when a transaction reexecutes a query and gets different rows as results because another transaction deleted or inserted rows in the meantime.
You can prevent this by using the SERIALIZABLE isolation level.
33. What is optimistic locking in JDBC?
Optimistic locking in JDBC is a strategy to handle concurrent updates without having to put heavy locks on the database rows. The idea behind it is that two users won’t try to update the same record at exactly the same time. So, instead of locking the rows in advance, the application simply checks if the data has been modified before applying the update.
This is usually implemented by adding a version column or timestamp to the table. If the version has changed, the update is rejected. JDBC itself doesn’t provide built-in optimistic locking. It’s implemented at the application or ORM layer (like Hibernate) by adding version/timestamp columns.
34. What is pessimistic locking in JDBC?
Pessimistic locking assumes that conflicts are common, i.e, two users are more likely to edit the same database at the same time. It locks the rows as soon as a transaction reads or modifies them. This prevents other transactions from accessing the rows until the lock is released. It ensures data integrity, but can cause blocking in high-traffic systems.
35. What is a two-phase commit in JDBC?
A two-phase commit (2PC) ensures consistency across multiple databases or systems.
- Prepare phase: The coordinator asks all databases if they can commit.
- Commit phase: if all agree, the commit happens; otherwise, a rollback is issued everywhere.
36. What are the different types of locking in JDBC?
- Row-level locking: Locks a single row, allowing higher concurrency.
- Table-level locking: Locks an entire table, simpler but less efficient.
Advanced JDBC Concepts (Experienced)
Senior roles or competitive interviews often go beyond the basics. You may be asked about connection pooling, distributed transactions, or handling multiple databases. This section dives into those advanced concepts that prove you can think like a professional developer, not just a student memorizing theory.
37. What is database connection pooling? What are its advantages?
Connection pooling is a technique where a pool of reusable database connections is maintained. Instead of creating a new connection for every request, the application borrows a connection from the pool and returns it after use.
38. How to achieve JDBC connection pooling using DataSource and JNDI in Apache Tomcat?
Tomcat comes built-in with connection pooling through JNDI (Java Naming and Directory Interface). Instead of creating a new database connection each time, you can define a reusable DataSource in Tomcat’s configuration.
Configure in context.xml (or server.xml)
<Resource name="jdbc/MyDB"
auth="Container"
type="javax.sql.DataSource"
maxTotal="20"
maxIdle="10"
driverClassName="com.mysql.cj.jdbc.Driver"
url="jdbc:mysql://localhost:3306/testdb"
username="root"
password="password"/>
- maxTotal → Maximum number of active connections in the pool.
- maxIdle → How many idle connections can be kept ready.
- Other attributes define driver details, database URL, and login credentials.
In Java code, you look it up:
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/MyDB");
Connection con = ds.getConnection();
39. What is Apache DBCP API?
Apache DBCP (Database Connection Pooling) API is a popular library that helps manage JDBC connections. What it essentially does is that it reuses connections instead of creating new ones every time, which can become expensive. This improves performance and reduces the overhead on the database.
It is highly reliable and is used in application servers like Apache Tomcat to handle a large number of requests without slowing down.
40. How do you connect to multiple databases simultaneously?
You can load multiple JDBC drivers and create separate Connection objects with different URLs. Each Connection corresponds to a different database.
Connection mysqlCon = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1", "user", "pwd");
Connection oracleCon = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "user", "pwd");
41. Using a single statement, can you update or extract data from multiple databases?
No, not directly. A JDBC Statement is tied to a single Connection, and a connection point is only to a single database. If you want to interact with multiple databases, you will need to create multiple connections.
42. What are common JDBC exceptions? Give examples.
Exception |
What It Means |
Example Scenario |
SQLException |
The base class for most database errors |
“Access denied for user” when wrong credentials are used |
SQLTransientException |
A temporary issue that might work if retried |
Network glitch while connecting to the DB |
SQLNonTransientException |
A permanent error that won’t succeed even if retried |
Wrong SQL syntax in a query |
SQLRecoverableException |
An error that can be corrected after corrective action |
Connection dropped; reconnect and try again |
43. What causes “No suitable driver found” error?
This error occurs when:
- The JDBC driver is not in the classpath.
- The connection URL is incorrect.
- The driver was not registered.
44. What is SQL Warning? How to retrieve warnings in JDBC?
SQLWarings are non-critical issues returned by the database. They do not stop execution, but should be checked. You can retrieve them using:
SQLWarning warning = stmt.getWarnings();
while (warning != null) {
System.out.println("Warning: " + warning.getMessage());
warning = warning.getNextWarning();
}
What is the difference between java.sql.Date and java.util.Date?
- java.sql.Date: A wrapper for SQL DATE, stores only year, month, and day (no time component).
- java.util.Date: Represents date and time down to milliseconds.
Usually, when working databases, you convert between them.
45. What are DML and DDL statements?
Category |
Purpose |
Common Commands |
DML (Data Manipulation Language) |
Works with the actual data stored in tables |
INSERT, UPDATE, DELETE, SELECT |
DDL (Data Definition Language) |
Defines or changes the structure/schema of database objects |
CREATE, ALTER, DROP, TRUNCATE |
46. Explain JDBC architecture briefly.
JDBC has two main layers:
- JDBC API: Interfaces like Connection, Statement, ResultSet.
- JDBC Driver API: Implements communication with the actual database.
This architecture allows Java applications to work with different databases without changing the underlying code.
47. Describe the life cycle of a JDBC application.
- Load and register driver
- Establish a connection
- Create a Statement
- Execute query/update
- Process the ResultSet
- Close ResultSet, Statement, and connection.
48. Explain try-with-resources in JDBC. Why is it important?
Try-with-resources automatically closes JDBC objects after use. This prevents resource leakage and performance issues. Any object that implements AutoClosable is automatically closed at the end of the try block, removing the need for explicit finally blocks. Example:
try (Connection con = ds.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT * FROM users");
ResultSet rs = ps.executeQuery()) {
while(rs.next()) {
System.out.println(rs.getString("name"));
}
}
49. What are the new features added in JDBC 4.0?
- Auto-loading of JDBC drivers (no Class.forName() needed).
- Enhanced SQLException hierarchy.
- Support for SQL XML data type via SQLXML.
- Annotations for SQL exceptions.
- New Wrapper and Unwrapper APIs.
Performance, Security, and Best Practices JDBC Interview Questions
Even if you can write working JDBC code, employers care about whether you can write efficient, secure, and maintainable code. This section focuses on best practices and common pitfalls, ensuring you’re ready to answer the tougher, practical questions that separate strong candidates from average ones.
50. Why are PreparedStatements faster than Statements?
PreparedStatements are precompiled on the database side. This means that the SQL query is parsed and optimized once, and can be executed multiple times with different parameters without re-parsing. This results in faster execution speed, reduced network traffic, and safer handling of special characters.
51. How do you prevent SQL injection vulnerabilities in JDBC applications?
SQL injection occurs when untrusted input is concatenated into a query string. You can prevent it by:
- Always using PreparedStatement instead of Statement.
- Avoid dynamic SQL with string concatenation.
- Validating and sanitizing user inputs.
52. What are JDBC best practices?
- Use connection pooling to reduce the overhead of frequent connection creation.
- Close resources in the finally block or use try-with-resources.
- Use PreparedStatement instead of Statement for dynamic queries.
- Handle exceptions gracefully and log them.
- Use batch processing for bulk inserts or updates,
- Manage transactions with setAutoCommit(false).
- Avoid hardcoding credentials; instead, use environment variables or configuration files.
- Choose proper isolation levels to balance performance and consistency.
53. What is the limitation of PreparedStatement, and how to overcome it?
PreparedStatement cannot dynamically change table name, column names, or SQL structure; it only supports substitution for values.
Workarounds:
- Use dynamic SQL carefully with string concatenation for table/column names, but ensure inputs are sanitized.
- For batch operations on multiple tables, you can dynamically construct the SQL string while still using parameterized values for user data.
54. Which is better for handling binary data: byte[] or Blob?
- byte[]: Suitable for small binary data (images, files under a few MB). Simple to use in memory.
- Blob: Better for large binary objects, as it streams data directly from/to the database without loading everything into memory.
Conclusion
Preparing for JDBC interview questions is not just about memorizing syntax; it’s about showing interviewers that you can think critically, manage data safely, and handle real-world database challenges with confidence. By mastering the fundamentals, understanding advanced concepts, and following best practices, you’ll be well ahead of the competition.
Remember, interviewers aren’t just testing what you know; they’re testing how you apply it. The fact that you’re reading this guide already puts you one step ahead of most candidates. Go through each section carefully, practice with real code, and walk into your interview with confidence. With preparation and the right mindset, that job offer is closer than you think.
Frequently Asked Questions
Q1. Is JDBC still used in 2025?
Yes, JDBC is still very relevant in 2025. Even though various frameworks like Hibernate, JPA, and Spring Data exist, they still work on top of JDBC. At its core, JDBC is what allows Java programs to communicate with relational databases.
Q2. Which JDBC driver is most commonly used?
The Type 4 driver (thin driver) is the most commonly used today. It’s platform-independent, written entirely in Java, and directly converts JDBC calls into database-specific protocol without needing native libraries. For example, the MySQL Connector/J and Oracle Thin Driver are both Type 4 drivers.
Q3. Can JDBC connect to any database?
Yes, JDBC can connect to almost any relational database, provided you have the right driver. Databases like MySQL, PostgreSQL, Oracle, SQL Server, and even newer cloud databases all provide JDBC drivers. As long as a vendor supplies a driver, you can use JDBC to interact with that database.
Q4. Is JDBC better than Hibernate?
Neither is strictly “better”; they serve different purposes. JDBC gives you low-level control over SQL queries, transactions, and database operations. Hibernate, on the other hand, abstracts a lot of that with ORM (Object Relational Mapping), reducing boilerplate code. Many interviewers expect you to understand JDBC first because frameworks like Hibernate are built on top of it.
Q5. How do I prepare for JDBC interviews as a fresher?
- Master the basics: Understand connections, statements, transactions, and ResultSet handling.
- Code small projects: Try building a student management system or employee database with JDBC.
- Practice interview questions: Go through common questions (like those in this guide).
- Focus on real-world use cases: Be ready to explain how you’d handle batch processing, transactions, and error handling.