Table of contents
1.
Introduction
2.
Components of JDBC
3.
Scope of JDBC
4.
JDBC Interview Questions for Freshers
4.1.
1. What is JDBC in Java?
4.2.
2. What are the JDBC API components?
4.3.
3. What is DriverManager in JDBC?
4.4.
4. Which JDBC driver is more effective and widely used?
4.5.
5. How can one connect to a database in Java, and what steps are involved?
4.6.
6. What types of data are used in the database table to store the image and file?
4.7.
7. Why are we utilizing DatabaseMetaData, and what do you mean by it?
4.8.
8. Explain JDBC Batch processing.
4.9.
9. Advantages of Batch processing.
4.10.
10. How to perform Batch processing?
4.11.
11. What is DataSource in JDBC?
4.12.
12. Benefits of DataSource
4.13.
13. Explain the usage of the getter and setter methods in ResultSet.
4.14.
14. What is database connection pooling?
4.15.
15. Advantages of the connection pool.
5.
JDBC Interview Questions for Experienced
5.1.
16. What is optimistic locking?
5.2.
17. What is pessimistic locking?
5.3.
18. What are the types of JDBC architecture?
5.4.
19. What is JDBC Transaction Management?
5.5.
20. Need for Transaction Management.
5.6.
21. What is a Two-phase commit in JDBC?
5.7.
22. What are the isolation levels of connections in JDBC?
5.8.
23. What is Result set and its types?
5.9.
24. Explain the distinctions among the execute, executeQuery, and executeUpdate methods?
5.10.
25. What advantages does PreparedStatement offer compared to Statement?
5.11.
26. Explain the differences between Statement and PreparedStatement interface?
5.12.
27. How can we execute stored procedures using CallableStatement?
5.12.1.
Create a Connection
5.12.2.
Prepare the CallableStatement
5.12.3.
Set Input Parameters
5.12.4.
Execute the CallableStatement
5.13.
28. Explain  the differences between ResultSet and RowSet?
5.14.
29. Explain the differences between Statement and PreparedStatement interface?
5.15.
30. What do you mean by JDBC statements?
6.
JDBC MCQ
6.1.
1. Which component of JDBC manages a list of database drivers?
6.2.
2. What does JDBC stand for?
6.3.
3. Which of the following is a valid JDBC driver type?
6.4.
4. What method is used to execute a SQL query in JDBC?
6.5.
5. Which JDBC object is used to store the result of an SQL query?
6.6.
6. Which exception is thrown when a database access error occurs in JDBC?
6.7.
7. What does the executeUpdate() method return?
6.8.
8. Which of the following methods is used to start a transaction in JDBC?
6.9.
9. What is the default state of auto-commit mode in JDBC?
6.10.
10. Which JDBC statement is used to call stored procedures?
7.
Conclusion
Last Updated: Sep 24, 2024
Easy

JDBC Interview Questions

Author Komal Shaw
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

JDBC is a Java Application Programming Interface (API) useful for communicating with databases and running SQL queries. The acronym JDBC stands for Java Database Connectivity. JDBC drivers are used to establish a connection to the database. Access to tabular data kept in relational databases like Oracle, MySQL, MS Access, etc. is made possible through JDBC API.

Top JDBC Interview Questions and Answers (2023)

Earlier, to establish a connection with the database and run the queries, the ODBC API was utilized as the database API. However, ODBC API for ODBC drivers employs C language (i.e. platform-dependent and unsecured). As a result, Java has developed its own JDBC API that uses JDBC drivers and provides a native Java interface for interacting with databases using SQL. For the creation of a "pure Java" solution, while employing Java programming, JDBC is necessary.

Components of JDBC

JDBC (Java Database Connectivity) is a Java-based API that allows applications to interact with various databases. The key components of JDBC are:

  1. Driver Manager: This component is responsible for managing a list of database drivers. It matches the appropriate driver for the database connection requests made by applications. It acts as an intermediary between the application and the database drivers.
  2. Driver: A JDBC driver is a set of classes that implement the JDBC interfaces for a particular database. There are four types of JDBC drivers, each providing different methods to connect to a database.
  3. Connection: The Connection object represents a session with a specific database. It is used to create statements, manage transactions, and communicate with the database.
  4. Statement: This component is used to execute SQL queries against the database. JDBC provides three types of statements: Statement, PreparedStatement, and CallableStatement. Each type is used for different kinds of SQL operations, including executing simple queries, precompiled queries, and stored procedures.
  5. ResultSet: The ResultSet object holds the data retrieved from a database after executing a query. It allows you to iterate over the results and retrieve the values from each column of the result set.
  6. SQLException: This component handles database-related errors. Whenever a database access error occurs, an SQLException is thrown, and it provides detailed information about the error.

Scope of JDBC

The scope of JDBC extends to any application that needs to interact with a relational database using Java. JDBC is a powerful tool for building:

  • Java Applications: JDBC is widely used in standalone Java applications to interact with databases for tasks like data retrieval, manipulation, and updates.
  • Web Applications: JDBC plays a crucial role in Java-based web applications, where server-side scripts and servlets frequently communicate with databases for dynamic content generation.
  • Enterprise Applications: JDBC is often used in large-scale enterprise applications that require extensive database interaction, such as ERP or CRM systems. It can be integrated into frameworks like Spring and Hibernate to streamline database operations.
  • Big Data Systems: JDBC can also be utilized in big data environments to connect Java applications with distributed databases like Apache Hive or HBase, enabling data analysis and processing.
  • Framework Support: Several Java frameworks (e.g., Spring) offer built-in support for JDBC, making database interaction more manageable and abstracting away low-level details while still utilizing the JDBC API.
     

There are some JDBC Interview Questions that are important and need to be done before an interview. So let us go through some of the top JDBC Interview questions.

JDBC Interview Questions for Freshers

Here are some JDBC Interview Questions. These JDBC Interview Questions need to be done thoroughly before an interview.

1. What is JDBC in Java?

A Java API called JDBC (Java Database Connectivity) is used for interacting with a database to access, modify, and process data using SQL. JDBC drivers will be used to connect to the database. We may access tabular data held in many relational databases, like Oracle, MySQL, MS Access, etc., by utilizing JDBC.

2. What are the JDBC API components?

The following are some of the main API components of JDBC:-

  • Driver Manager: The DriverManager class manages a list of database drivers. It is responsible for establishing a connection to the database.
     
  • JDBC Drivers: JDBC drivers are platform-specific implementations that allow Java applications to connect to a particular database system.
     
  • Connection Interface: The Connection interface represents a connection to a specific database. It is obtained from the DriverManager and used to create Statement objects and manage transactions.
     
  • Statement Interface: The Statement interface is used to execute SQL queries on the database.
     
  • ResultSet Interface: The ResultSet interface represents the result set of a SQL query. It provides methods for iterating through the rows of the result set.

3. What is DriverManager in JDBC?

Ans: Java's static JDBC DriverManager class is used to control the selection of JDBC drivers that are accessible to applications. An application can use many JDBC drivers at once if necessary. Each application identifies a JDBC driver by utilizing a Uniform Resource Locator (URL).
Using Class.forName() or DriverManager.registerDriver(), the JDBC Driver class registers itself with the DriverManager when it is loaded into an application (). You can examine the JDBC Driver classes' source code to verify this. After that, DriverManager will use registered drivers to retrieve the connection and deliver it to the calling program when we execute the DriverManager.getConnection() method and send the database configuration information to it.

4. Which JDBC driver is more effective and widely used?

The JDBC Net pure Java driver (Type 4 driver) directly communicates with the database by translating JDBC calls into vendor-specific protocol calls, making it the quickest driver for localhost and remote connections.

5. How can one connect to a database in Java, and what steps are involved?

To connect to a database in Java using JDBC, you need the following steps:-

  • Load the JDBC Driver: Load the appropriate JDBC driver for your database. This step is usually optional in modern JDBC implementations, as drivers can be automatically loaded, but it's a good practice to include it.
     
  • Establish a Connection: Use the DriverManager to create a database connection by providing the database URL, username, and password.
String url = "your database URL"
String username = "yourusername";
String password = "yourpassword";

Connection connection = DriverManager.getConnection(url, username, password);

 

With the returned connection, you can create statements to execute SQL queries.

6. What types of data are used in the database table to store the image and file?

The image is kept in the database using the BLOB data type. The BLOB data type can be used to hold audio and video files as well. Data of the binary kind is stored there. The file is kept in the database using the CLOB data type. It keeps data of the character type.

7. Why are we utilizing DatabaseMetaData, and what do you mean by it?

An interface called DatabaseMetaData offers ways to find out information about the database. This can be used to obtain database-related data such as the name of the database, its version, the name of the driver, the total number of tables or views, etc.

8. Explain JDBC Batch processing.

Executing several SQL statements simultaneously is known as batch processing. Take the scenario of importing data from CSV (Comma-Separated Values) files into relational database tables as an example. We can utilize batch processing, which executes the majority of queries for a database in one go, in place of Statement or PreparedStatement.

9. Advantages of Batch processing.

It will cut down on communication time while enhancing performance. Large amounts of data can be processed more quickly and consistently with batch processing. Due to the reduced amount of database calls, it is substantially faster than processing one statement at a time.

10. How to perform Batch processing?

The methods addBatch() and executeBatch() are used for batch processing. The Statement and PreparedStatement classes of the JDBC API contain these 2 methods.

11. What is DataSource in JDBC?

The javax.sql package contains an interface called DataSource that is used to retrieve the database connection. It can be utilized as a decent DriverManager class substitute since it gives your application program access to database information.
The DriverManager does not register a driver that is accessed through a DataSource object. Instead, a lookup operation is utilized to retrieve a DataSource object, which may then be used to generate a Connection object.

12. Benefits of DataSource

Caching of PreparedStatement for faster processing
Logging features
Connection timeout settings
ResultSet maximum size threshold
Connection Pooling in servlet container using the support of JNDI registry. 

13. Explain the usage of the getter and setter methods in ResultSet.

Getter methods: These are used to get specific table column values from the ResultSet. Either the column name or the column index value should be given as a parameter. The getter method is typically represented by the getXXX() methods.
Example:
int getInt(string columnName)

Setter Methods: 
The value in the database is set using these techniques. It is almost identical to getter methods, but in this case, you must also give the name of the column or its index value in addition to the data or values for the specific column you want to insert into the database. Setter methods are typically represented as setXXX() methods.
Example:
void setInt(int columnIndex, int dataValue)

14. What is database connection pooling?

When connection pooling is implemented, database connections are saved in the cache and can be re-used for subsequent database requests. The client does not have to establish new connections each time to interact with the database with this approach. In its place, connection objects are kept in the connection pool and are obtained by the client from there.

15. Advantages of the connection pool.

It is faster.
Analyzing and diagnosing database connections is made simpler.
Improves the speed at which commands are carried out on databases. 

JDBC Interview Questions for Experienced

16. What is optimistic locking?

Only when an update occurs will the record be locked. When reading or selecting the record, this sort of locking will not use exclusive locks.

17. What is pessimistic locking?

As soon as it chooses the row to update, it locks the record. The design of this locking mechanism ensures that the modifications are carried out reliably and safely.

18. What are the types of JDBC architecture?

Two-tier Architecture: Here, the database and Java programs are explicitly linked. Except for the JDBC driver, no intermediary is needed to connect to the database, such as an application server. Another name for it is a client-server architecture.

Three-tier Architecture: In contrast to two-tier architecture, it is completely different. The Java application or JDBC driver won't explicitly communicate with the database. It will act as a bridge between them by using an application server. An application server will forward the request to the database via Java code, and the server will then get the response from the database.

19. What is JDBC Transaction Management?

A transaction is a name given to the series of operations (SQL statements) that made up the transaction. In RDBMS-oriented systems, transaction management plays a crucial role in preserving the consistency and integrity of the data.

20. Need for Transaction Management.

The auto-commit mode will be chosen by default when initiating a connection to the database. This implies that each time the request is processed, it will be immediately committed when finished.
The transaction may need to be committed once a few more SQL statements have been executed. We must set the auto-commit value to False in such a case. As a result, the data cannot commit until all of the queries have been run. If there is an exception during the transaction, we can rollback() the modifications and restore the previous state.

21. What is a Two-phase commit in JDBC?

In a distributed context where several processes participate in the distributed transaction process, a two-phase commit is beneficial. Simply put, a two-phase commit will be utilized to ensure that all databases are in synchronization with one another while a transaction is active and it affects several databases.

In a two-phase commit, the following two phases are used to accomplish the commit or rollback:
Commit request phase: In this phase, the primary process or coordinator process asks all other processes to vote on whether or not they have successfully finished their processes and are prepared to commit. If all the votes are "yes," they move on to the next phase. If "No," rollback will be carried out.
Commit Phase: If every vote is "yes," commit is completed.

Similar to this, whenever a transaction modifies several databases after it has been executed, it issues a pre-commit instruction to each database and requests an acknowledgment from each database. If all of the transactions are positive upon acknowledgment, the commit instruction will be sent; otherwise, a rollback will be carried out.

22. What are the isolation levels of connections in JDBC?

The transaction isolation level determines the threshold at which inconsistent data is allowed in a transaction, determining the degree to which one transaction is isolated from another. Data correctness will increase with increased isolation, but there is a chance that fewer concurrent transactions may occur. Comparably, although allowing for more concurrent transactions, a lesser level of isolation compromises data accuracy.
The DBMS uses locks to restrict access to the data that is involved in the transaction in order to maintain data integrity during JDBC transactions. These locks are required to protect the database from Dirty Read, Non-Repeatable Read, and Phantom-Read.
It can be set using the setTransactionIsolation() method and is used by DBMS as part of the locking mechanism. Utilizing the getTransactionIsolation() method, you may learn more about the isolation level that the connection is using.

23. What is Result set and its types?

A result set is an object that represents the data retrieved from a database after a query operation. Below are some common types of result sets:

  • Single-Row Result Set: This type of result set contains a single row of data.
  • Multi-Row Result Set: This result set contains multiple rows of data.
  • Empty Result Set: An empty result set denotes that there are no rows in the database.
  • Update Result Set: This result set provides you to read as well as modify the data in the result set.

24. Explain the distinctions among the execute, executeQuery, and executeUpdate methods?

  • Execute: Use execute when there is a need to handle both the queries and updates and you want to execute any SQL query.
  • ExecuteQuery: This query returns a ResultSet object with containing the query result. You can use this when you want to execute a SELECT statement.
  • ExecuteUpdate: You can use this, when you want to execute SQL statements that modify the database.

25. What advantages does PreparedStatement offer compared to Statement?

PreparedStatement offers advantages as compared to Statement are performance improvement, preventing SQL injection attacks, query optimization, improving code readability, and batch processing.

26. Explain the differences between Statement and PreparedStatement interface?

  • PreparedStatement allows parameter blinding and enables the use of placeholders for dynamic values. While Statement does not support parameterization.
  • PreparedStatement can execute multiple times. On the other hand, Statement needs to optimize the SQL statement every time.
  • PreparedStatement offers better performance than Statement.
  • PreparedStatement support parameter binding, which prevents SQL injection attacks. While Statement does not offer this protection.

27. How can we execute stored procedures using CallableStatement?

To execute stored procedures using JDBC with a CallableStatement, you should follow these steps:-

Create a Connection

Establish a database connection using the driver manager.

Prepare the CallableStatement

Create a CallableStatement by specifying the SQL statement that calls the stored procedure. The following syntax uses “?” as the parameter placeholders.

CallableStatement callableStatement = connection.prepareCall("{call your_stored_procedure(?, ?, ?)}");

Set Input Parameters

If your stored procedure has input parameters, use the "set()" methods of the `CallableStatement` to set their values like the following.

callableStatement.setInt(1, parameter1Value);
callableStatement.setString(2, parameter2Value);
callableStatement.setDouble(3, parameter3Value);

Execute the CallableStatement

After setting the required input parameters, you can execute the stored procedure using the "execute()" or "executeQuery()" method of the CallableStatement.

callableStatement.execute();

28. Explain  the differences between ResultSet and RowSet?

Feature ResultSet RowSet
Scrollability It is typically forward-only, allowing iteration through rows in one direction. RowSet can be configured as scrollable, enabling forward and backward navigation through rows.
Updatability ResultSet is read-only. RowSet can be configured to be updatable.
Connectivity ResultSet is always connected to the database. RowSet can either be connected or disconnected.
Synchronization To persist changes, you need separate SQL statements. RowSet can automatically generate SQL statements for database updates.
Ease of use ResultSet provides a low-level interface which needs more manual coding. RowSet offers higher level abstraction with methods for pagination, sorting, etc.

29. Explain the differences between Statement and PreparedStatement interface?

Feature Statement PreparedStatement
SQL Injection Statement is vulnerable to SQL injection attacks. This provides protection against SQL injection with the help of parameterized queries.
Query Execution Queries are compiled and executed each time they are called, making it less efficient for repetitive queries. Queries are precompiled and reused with different parameters.
Code Readability Queries are embedded as strings within the Java code, which makes it less readable. Queries are separate from Java code, making it more maintainable.
Performance Performance may be lower for frequently executed queries due to the compilation overhead. PreparedStatements offers better performance.

30. What do you mean by JDBC statements?

JDBC stands for Java Database Connectivity. It refers to the objects that are used to execute SQL commands against a database. You can execute the SQL statement using methods like executeQuery(), execute(), or executeUpdate() once the JDBC statement is created.

JDBC MCQ

1. Which component of JDBC manages a list of database drivers?

A. Connection
B. Statement
C. Driver Manager
D. ResultSet

Answer: C. Driver Manager

2. What does JDBC stand for?

A. Java Database Communication
B. Java Data Control
C. Java Database Connectivity
D. Java Data Collection

Answer: C. Java Database Connectivity

3. Which of the following is a valid JDBC driver type?

A. Type 0
B. Type 1
C. Type 5
D. Type 6

Answer: B. Type 1

4. What method is used to execute a SQL query in JDBC?

A. execute()
B. query()
C. runSQL()
D. runQuery()

Answer: A. execute()

5. Which JDBC object is used to store the result of an SQL query?

A. Connection
B. ResultSet
C. Statement
D. Driver

Answer: B. ResultSet

6. Which exception is thrown when a database access error occurs in JDBC?

A. IOException
B. SQLException
C. ClassNotFoundException
D. FileNotFoundException

Answer: B. SQLException

7. What does the executeUpdate() method return?

A. The number of rows affected
B. A ResultSet object
C. A SQL query
D. A Connection object

Answer: A. The number of rows affected

8. Which of the following methods is used to start a transaction in JDBC?

A. beginTransaction()
B. commit()
C. setAutoCommit(false)
D. start()

Answer: C. setAutoCommit(false)

9. What is the default state of auto-commit mode in JDBC?

A. True
B. False
C. Undefined
D. Not applicable

Answer: A. True

10. Which JDBC statement is used to call stored procedures?

A. PreparedStatement
B. Statement
C. CallableStatement
D. ResultSet

Answer: C. CallableStatement

Conclusion

In this article, we have discussed JDBC Interview Questions. Understanding the core elements such as drivers, connection management, SQL execution, and handling exceptions is crucial for anyone working with database-driven Java applications. Whether you're preparing for a job interview or simply enhancing your knowledge of JDBC, these questions and answers will help solidify your understanding of how JDBC integrates with databases and enables seamless data interaction.

Also, do refer to JDBC Interview Questions related articles:

 

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc.

Enrol in our courses and refer to the mock test and problems available.

Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow.

Happy Coding!

Live masterclass