0 Comments

Introduction to JDBC Interview Questions

JDBC (Java Database Connectivity) is a Java API used to connect and execute queries with databases. It is a crucial topic for Java developers, database engineers, and backend developers.

This guide covers 30+ JDBC interview questions ranging from basic concepts to advanced topics like connection pooling, transactions, and batch processing.


Section 1: JDBC Basics (10 Questions)

1. What is JDBC?

JDBC (Java Database Connectivity) is a Java API that enables Java applications to interact with relational databases using SQL queries.

2. What are the main components of JDBC?

  • DriverManager – Manages database drivers
  • Connection – Establishes a session with the database
  • Statement – Executes SQL queries
  • ResultSet – Stores query results

3. What are the different types of JDBC drivers?

TypeDescription
Type 1JDBC-ODBC Bridge (Deprecated)
Type 2Native API (Part Java, Part Native)
Type 3Network Protocol (Middleware-based)
Type 4Pure Java (Direct-to-DB)

4. How do you load a JDBC driver?

Class.forName("com.mysql.jdbc.Driver"); // Older way (JDBC 3.0)

In JDBC 4.0+, drivers are auto-loaded via ServiceLoader.

5. How to establish a JDBC connection?

String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "password";
Connection conn = DriverManager.getConnection(url, user, password);

6. What is the difference between Statement, PreparedStatement, and CallableStatement?

TypeUse Case
StatementSimple SQL (no parameters)
PreparedStatementParameterized SQL (prevents SQL injection)
CallableStatementExecutes stored procedures

7. How to execute a SELECT query in JDBC?

Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
while (rs.next()) {
    System.out.println(rs.getString("name"));
}

8. What is a ResultSet in JDBC?

ResultSet is a table-like object that stores the results of a SQL query.

9. How to handle transactions in JDBC?

conn.setAutoCommit(false); // Disable auto-commit
try {
    stmt.executeUpdate("INSERT INTO users VALUES (1, 'John')");
    conn.commit(); // Commit on success
} catch (SQLException e) {
    conn.rollback(); // Rollback on failure
}

10. How to close JDBC resources properly?

Use try-with-resources (Java 7+) to auto-close connections:

try (Connection conn = DriverManager.getConnection(url, user, password);
     Statement stmt = conn.createStatement()) {
    // JDBC operations
} catch (SQLException e) {
    e.printStackTrace();
}

Section 2: Advanced JDBC (10 Questions)

11. What is JDBC Connection Pooling?

Connection pooling reuses database connections to improve performance (e.g., HikariCP, Apache DBCP).

12. What is a DataSource in JDBC?

DataSource is an alternative to DriverManager and supports connection pooling.

13. How to prevent SQL Injection in JDBC?

Use PreparedStatement instead of Statement:

PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users WHERE id = ?");
pstmt.setInt(1, userId);

14. What is Batch Processing in JDBC?

Batch processing groups multiple SQL queries into a single execution:

PreparedStatement pstmt = conn.prepareStatement("INSERT INTO employees VALUES (?, ?)");
pstmt.setInt(1, 101);
pstmt.setString(2, "Alice");
pstmt.addBatch(); // Add to batch
pstmt.executeBatch(); // Execute all at once

15. What are Scrollable and Updatable ResultSets?

  • Scrollable ResultSet → Can move forward/backward (TYPE_SCROLL_INSENSITIVE)
  • Updatable ResultSet → Can modify data (CONCUR_UPDATABLE)

16. What is JDBC RowSet?

RowSet is a wrapper for ResultSet with additional features (disconnected mode, JavaBean support).

17. How to call a stored procedure in JDBC?

CallableStatement cstmt = conn.prepareCall("{call get_employee(?)}");
cstmt.setInt(1, empId);
ResultSet rs = cstmt.executeQuery();

18. What is Metadata in JDBC?

  • DatabaseMetaData → Database info (tables, schemas)
  • ResultSetMetaData → ResultSet structure (columns, types)

19. What are the common JDBC Exceptions?

  • SQLException – General database error
  • SQLTimeoutException – Query timeout
  • BatchUpdateException – Batch execution failure

20. How to improve JDBC performance?

  • Use connection pooling
  • Optimize SQL queries
  • Use batch processing
  • Fetch only required columns

People Also Ask (10 Additional Questions)

JDBC Best Practices

  1. Should we use Class.forName() in JDBC 4.0+?
    No, auto-loading is supported in JDBC 4.0+.
  2. How to handle large data in JDBC?
    Use setFetchSize() to control row retrieval.
  3. What is the difference between execute(), executeQuery(), and executeUpdate()?
  • executeQuery() → SELECT
  • executeUpdate() → INSERT, UPDATE, DELETE
  • execute() → Any SQL

JDBC vs. Other Technologies

  1. JDBC vs. Hibernate?
  • JDBC → Low-level SQL control
  • Hibernate → ORM (Object-Relational Mapping)
  1. JDBC vs. JPA?
  • JDBC → Manual SQL handling
  • JPA → Higher-level abstraction (Hibernate, EclipseLink)

Troubleshooting JDBC

  1. How to debug JDBC connection issues?
    Check:
  • URL, username, password
  • Firewall/network access
  • Driver compatibility
  1. What causes “No suitable driver found” error?
  • Missing JDBC driver in classpath
  • Incorrect JDBC URL

Advanced JDBC Features

  1. Does JDBC support NoSQL databases?
    Some NoSQL databases (MongoDB, Cassandra) provide JDBC-like drivers.
  2. What is XA Datasource in JDBC?
    Used in distributed transactions (JTA).
  3. How to use JDBC with Spring Framework?
  • JdbcTemplate (Simplifies JDBC operations)
  • Spring Data JDBC (ORM alternative)

Conclusion

This comprehensive JDBC interview guide covers 30+ essential questions on:
✔ JDBC Basics (Connection, Statements, ResultSet)
✔ Advanced JDBC (Connection Pooling, Batch Processing)
✔ Best Practices & Troubleshooting

Next Steps:

  • Practice JDBC coding examples
  • Explore HikariCP for connection pooling
  • Learn Spring JDBC for enterprise apps

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts