JDBC (Java Database Connectivity) is a Java API that enables Java applications to communicate with relational databases. It provides a standard set of interfaces and classes to establish database connections, execute SQL queries, retrieve results, and manage transactions.
Using JDBC, developers can perform:
- Insert records
- Update records
- Delete records
- Retrieve data
- Execute stored procedures
- Manage transactions
Top JDBC Interview Questions
1. What is JDBC?
JDBC is a standard Java API used for database connectivity. It allows Java programs to interact with relational databases using SQL statements.
Advantages include:
- Database-independent programming
- Secure database communication
- Standard API across different databases
- Support for transactions and batch processing
2. What are the main components of JDBC?
The primary JDBC components are:
- DriverManager
- Driver
- Connection
- Statement
- PreparedStatement
- CallableStatement
- ResultSet
- SQLException
These components work together to establish connections and execute SQL operations.
3. What are the steps to connect a Java application to a database?
The typical JDBC workflow is:
- Import JDBC packages.
- Load the JDBC driver (optional for modern JDBC drivers).
- Establish a database connection.
- Create a statement.
- Execute SQL queries.
- Process the results.
- Close resources.
4. What is a JDBC Driver?
A JDBC Driver is a software component that enables Java applications to communicate with a specific database.
Popular JDBC drivers include:
- MySQL JDBC Driver
- Oracle JDBC Driver
- PostgreSQL JDBC Driver
- Microsoft SQL Server JDBC Driver
5. What are the types of JDBC Drivers?
There are four types of JDBC drivers:
Type 1 – JDBC-ODBC Bridge Driver
- Uses ODBC
- Deprecated
- Not recommended
Type 2 – Native API Driver
- Uses native database libraries
- Platform dependent
Type 3 – Network Protocol Driver
- Uses middleware server
- Suitable for distributed applications
Type 4 – Thin Driver
- Pure Java implementation
- Direct communication with the database
- Most widely used today
6. What is DriverManager?
DriverManager is a JDBC class responsible for managing database drivers and creating database connections.
Example:
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/company",
"root",
"password"
);
7. What is a Connection object?
A Connection object represents an active connection between a Java application and a database.
It is used to:
- Create statements
- Manage transactions
- Commit or rollback changes
- Close the database connection
8. What is the difference between Statement and PreparedStatement?
| Statement | PreparedStatement |
|---|---|
| SQL written at runtime | Precompiled SQL |
| Slower | Prevents SQL Injectiontd> |
| Suitable for static SQL | Suitable for dynamic SQL with parameters |
9. Why is PreparedStatement preferred?
PreparedStatement offers several advantages:
- Better performance
- Prevents SQL Injection attacks
- Supports parameterized queries
- Easier to reuse
- Improves readability
Example:
PreparedStatement ps = connection.prepareStatement(
"SELECT * FROM employee WHERE id = ?"
);
ps.setInt(1, 101);
ResultSet rs = ps.executeQuery();
10. What is CallableStatement?
CallableStatement is used to execute stored procedures in the database.
Example:
CallableStatement cs =
connection.prepareCall("{call getEmployees()}");
ResultSet rs = cs.executeQuery();
11. What is ResultSet?
ResultSet represents the data returned from a SQL query.
Example:
while(rs.next()){
System.out.println(rs.getString("name"));
}
Common methods:
- next()
- previous()
- first()
- last()
- getInt()
- getString()
12. What are the types of ResultSet?
Based on Cursor Movement
- TYPE_FORWARD_ONLY
- TYPE_SCROLL_INSENSITIVE
- TYPE_SCROLL_SENSITIVE
Based on Updatability
- CONCUR_READ_ONLY
- CONCUR_UPDATABLE
13. What is the difference between execute(), executeQuery(), and executeUpdate()?
| Method | Purpose | |
|---|---|---|
| execute() | Executes any SQL statement | |
| executeQuery() | Executes SELECT queries | |
| executeUpdate() | Executes INSERT, UPDATE, DELETE, and DDL statements |
14. What is batch processing in JDBC?
Batch processing allows multiple SQL statements to be executed together, improving performance.
Example:
PreparedStatement ps = connection.prepareStatement(
"INSERT INTO employee(name) VALUES (?)"
);
ps.setString(1, "John");
ps.addBatch();
ps.setString(1, "Alice");
ps.addBatch();
ps.executeBatch();
Benefits:
- Faster execution
- Reduced database calls
- Improved performance
15. What is transaction management?
A transaction is a group of SQL operations executed as a single unit.
Transaction methods:
- commit()
- rollback()
- setAutoCommit(false)
Example:
connection.setAutoCommit(false);
// Execute SQL statements
connection.commit();
16. What is auto-commit mode?
By default, JDBC runs in auto-commit mode, meaning every SQL statement is committed immediately after execution.
Disable it using:
connection.setAutoCommit(false);
17. What is rollback?
rollback() undoes all changes made during the current transaction if an error occurs.
Example:
connection.rollback();
This helps maintain data consistency.
18. What is SQLException?
SQLException is the exception thrown when a database access error occurs.
Common causes:
- Invalid SQL syntax
- Connection failure
- Constraint violations
- Missing tables
- Authentication issues
19. What is connection pooling?
Connection pooling maintains a pool of reusable database connections instead of creating a new connection for every request.
Advantages:
- Faster performance
- Reduced connection overhead
- Better scalability
- Improved resource management
Popular connection pool libraries:
- HikariCP
- Apache DBCP
- C3P0
20. What is SQL Injection?
SQL Injection is a security vulnerability where malicious SQL code is injected into user input.
Unsafe example:
String query =
String query =
"SELECT * FROM users WHERE username = '" + username + "'";
Safe approach:
Use PreparedStatement with parameters.
21. What is metadata in JDBC?
JDBC provides metadata about databases and query results.
Common metadata classes:
- DatabaseMetaData
- ResultSetMetaData
These help retrieve information about tables, columns, drivers, and database capabilities.
22. How do you close JDBC resources?
Resources should always be closed after use.
Order of closing:
- ResultSet
- Statement / PreparedStatement
- Connection
Modern Java recommends using try-with-resources.
Example:
try (
Connection con = DriverManager.getConnection(url, user, password);
PreparedStatement ps = con.prepareStatement("SELECT * FROM employee");
ResultSet rs = ps.executeQuery()
) {
while (rs.next()) {
System.out.println(rs.getString("name"));
}
}
23. What is the difference between Statement and CallableStatement?
| Statement | CallableStatement | |
|---|---|---|
| Executes SQL queries | Executes stored procedures | |
| Simpler operations | Supports IN, OUT, and INOUT parameters | |
| No stored procedure support | Designed for stored procedures |
24. What are the best practices when using JDBC?
Some recommended practices include:
- Use PreparedStatement instead of Statement.
- Close resources using try-with-resources.
- Use connection pooling in production applications.
- Handle exceptions properly.
- Avoid hardcoding database credentials.
- Use transactions where required.
- Validate user input.
- Keep SQL statements readable and maintainable.
25. Which JDBC topics are asked most frequently in interviews?
Interviewers commonly ask about:
- JDBC Architecture
- JDBC Drivers
- Statement vs PreparedStatement
- PreparedStatement vs CallableStatement
- ResultSet
- Transactions
- Batch Processing
- Connection Pooling
- SQL Injection Prevention
- Auto-Commit
- SQLException
- Try-with-Resources
Tips to Crack JDBC Interviews
- Understand the complete JDBC architecture.
- Learn the lifecycle of a database connection.
- Practice writing CRUD operations using JDBC.
- Understand transactions and rollback.
- Know why PreparedStatement is preferred.
- Learn batch processing and connection pooling.
- Be familiar with ResultSet navigation methods.
- Practice connecting Java applications with MySQL or PostgreSQL.
Frequently Asked Questions (FAQs)
Why is JDBC important in Java interviews?
JDBC is the standard API for interacting with relational databases. Since most enterprise Java applications work with databases, interviewers expect developers to understand JDBC concepts and best practices.
Which JDBC topic is asked most often?
The most frequently asked topics include:
- Statement vs PreparedStatement
- JDBC Drivers
- ResultSet
- Transaction Management
- Batch Processing
- SQL Injection
- Connection Pooling
- Auto-Commit
- CallableStatement
Is JDBC still relevant if we use Hibernate or Spring Data JPA?
Yes. Frameworks like Hibernate and Spring Data JPA internally rely on JDBC to communicate with databases. Understanding JDBC helps you troubleshoot database issues, optimize queries, and better understand how higher-level frameworks work.
Conclusion
JDBC remains a fundamental technology for Java developers working with relational databases. A solid understanding of JDBC architecture, drivers, statements, transactions, batch processing, connection pooling, and exception handling will help you build efficient, secure, and scalable database applications. During interviews, focus on explaining concepts with practical examples and be prepared to discuss real-world scenarios involving database connectivity. Mastering JDBC will strengthen your Core Java knowledge and improve your confidence in backend development interviews.