Common JDBC Interview Questions to Expect in 2023 - IQCode's Expert Guide

Introduction to Java Database Connectivity (JDBC)

JDBC is an Application Programming Interface (API) for Java that enables communication with a database and execution of SQL queries. It stands for Java Database Connectivity and is used to access tabular data stored in relational databases such as Oracle, MySQL, MS Access, etc.

Components of JDBC

JDBC comprises four major components:

  1. JDBC API: It provides different methods and interfaces for easy communication with the database. This enables applications to execute SQL statements, retrieve results, and make updates to the database. It consists of two packages: java.sql.* and javax.sql.*, which exhibit Write Once Run Everywhere (WORA) capabilities for both Java SE and Java EE platforms. JDBC API also provides a standard for connecting a database to a client application.
  2. JDBC DriverManager: It is the class in the JDBC API that loads the JDBC driver in a Java application for establishing a connection with the database. It is useful in making a database-specific call for processing the user request.
  3. JDBC Test Suite: It is used to test the operations like insertion, deletion, and updation performed by JDBC drivers.
  4. JDBC-ODBC Bridge Drivers: It connects database drivers to the database. The JDBC-ODBC bridge interprets JDBC method calls to the ODBC function call. It uses the sun.jdbc.odbc package, which consists of the native library to access characteristics of ODBC.

Scope of JDBC

Earlier, ODBC API was used as the database API to connect with the database and execute queries. But, ODBC API uses C language for ODBC drivers, which is platform-dependent and unsecured. Hence, Java has defined its own JDBC API that uses JDBC drivers, which offer a natural Java interface for communicating with the database through SQL. JDBC is required to provide a "pure Java" solution for the development of an application using Java programming.

JDBC Interview Questions for Freshers

  1. What is JDBC in Java?

What is ResultSet?

ResultSet is an interface in Java that provides methods to traverse and manipulate data returned from a database query. It maintains a cursor that points to the current row in the result set and allows the application to move the cursor forwards, backwards, and to arbitrary positions within the result set. The ResultSet object represents a table of data which is retrieved from the database and stored in memory for further processing by the Java application. It contains metadata about the result set such as the number of rows, columns, and data types of each column. The ResultSet interface is provided by the JDBC (Java Database Connectivity) API and can be implemented by different JDBC drivers to provide access to different types of databases.

JDBC Driver: An Overview

JDBC (Java Database Connectivity) is a Java API that provides a standard way to interact with a database from a Java application. A JDBC driver is a software component that allows Java applications to connect to a database, send queries, and retrieve results.

JDBC drivers can be classified into four types:

1. Type 1: JDBC-ODBC Bridge driver 2. Type 2: Native-API/partly Java driver 3. Type 3: Network-Protocol driver (middleware driver) 4. Type 4: Native-Protocol driver (pure Java driver)

Each type of JDBC driver has its own advantages and disadvantages, depending on the application's needs and the database being used. It's important to choose the appropriate driver for the task at hand to ensure optimal performance and reliability.

Overall, JDBC drivers are an essential component in Java/Database communication, allowing for the seamless integration of database functionality into Java applications.

What is DriverManager in JDBC?

In JDBC (Java Database Connectivity), DriverManager is a class in the java.sql package that manages a list of database drivers. It is responsible for finding an appropriate database driver from the list of registered drivers and creating a connection to the database. The DriverManager class uses a service provider mechanism to locate and load the JDBC drivers that are registered with it. Once a suitable driver is found, the DriverManager establishes a connection to the database using the necessary parameters, such as the database URL, username, and password.

Which JDBC Driver is the Fastest and Most Commonly Used?

When it comes to JDBC drivers, the answer can depend on the specific situation and database being used. However, in general, the Type 4 JDBC driver is considered the fastest and most commonly used driver. This is because it is written entirely in Java and interacts directly with the database through JDBC, without needing any external libraries or APIs. Additionally, Type 4 drivers generally support newer versions of JDBC and the Java language itself. It's important to do your own research and testing to determine the best JDBC driver for your specific needs.

Which Data Types are Used for Storing Images and Files in a Database Table?

In databases, images and files are usually stored using the BLOB (Binary Large Object) data type. The BLOB data type is capable of storing large binary objects, including images, audio, video, and other multimedia files. Some databases also have specific data types such as VARBINARY or LONGVARBINARY that can be used to store binary data. It is important to properly configure the database settings and tables to ensure efficient storage and retrieval of these large data objects.

Stored Procedures: Definition and Parameter Types

A stored procedure is a set of SQL statements that are stored as a named routine in a database. Stored procedures are used to perform repetitive tasks, encapsulate business logic, and improve database performance.

There are three types of parameters that can be used in stored procedures: 1. IN parameters - used to pass input values to the stored procedure 2. OUT parameters - used to return a single value from the stored procedure 3. INOUT parameters - used to pass input values to the stored procedure and return multiple values from the stored procedure.

These parameters can be used to create dynamic SQL queries and provide greater flexibility to the stored procedure. Additionally, stored procedures can use control structures such as if/else statements and loops, making them more powerful than simple SQL statements.

Understanding DatabaseMetadata and Its Purpose

DatabaseMetadata is a component of JDBC API that provides metadata about the database like schemas, tables, columns, and their attributes. It is used to get information about the database to dynamically interact with it using Java code. The metadata retrieved can be used for various purposes like generating reports, querying the database, and data mapping. By utilizing DatabaseMetadata, we can create more efficient and scalable applications that can easily adapt to changes within the database.

Differences between ODBC and JDBC

ODBC and JDBC are both APIs used to connect with relational databases from different programming languages. However, there are some key differences between the two:

- ODBC is mostly used in Windows platforms while JDBC is used in Java-based platforms. - ODBC drivers are specific to a particular database management system while JDBC drivers are developed using Java Database Connectivity API and are platform-independent. - JDBC is easier to learn and use compared to ODBC. - ODBC supports a wide range of database management systems including Microsoft Access, SQL Server, Oracle, and MySQL while JDBC is mostly used with Java-enabled databases like MySQL, Oracle, and Apache Derby.

In conclusion, while both APIs have their own set of advantages and disadvantages, choosing between ODBC and JDBC will mostly depend on the platform and database management systems being used.

JDBC Interview Questions for Experienced

One of the questions that may come up during a JDBC interview is regarding the different types of JDBC drivers in Java. Below are the different types and their explanations with examples:

// Type 1: JDBC-ODBC Bridge Driver
// This is an old driver that is now deprecated, recommended to avoid using it.
// Example:
Connection con = DriverManager.getConnection("jdbc:odbc:myDSN","username","password");

// Type 2: Native-API Driver
// This requires the installation of a vendor-specific API on the computer that connects to the database.
// Example:
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","username","password");

// Type 3: Network Protocol Driver
// This driver uses a middleware that converts the request from JDBC into the vendor-specific database protocol.
// Example:
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","username","password");

// Type 4: Thin Driver
// This driver is also known as a "Pure Java Driver" and it converts the request from JDBC into the vendor-specific database protocol.
// Example:
Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/mydb","username","password");

These are the different types of JDBC drivers in Java. It is important to have a clear understanding of each type to effectively use JDBC in your applications and to perform well in JDBC interviews.

H3 Difference between ResultSet and RowSet

In Java, the ResultSet and RowSet interfaces are used to retrieve and manipulate data from a database. The main difference between them is that the ResultSet is a standard interface that provides read-only access to a database's tabular data, whereas the RowSet extends the ResultSet interface to provide more flexibility, such as updateable, scrolling version of the ResultSet, which is disconnected from the database.

In other words, ResultSet is a pointer to a database result set, which can only be navigated forward, while connected to the database. Once the connection is closed, the ResultSet object becomes obsolete. On the other hand, RowSet is a JavaBeans component that stores a result set in memory, which can be manipulated without a connection to the database. It can be used to perform offline operations on the data retrieved from a database, and sync it back to the database when a connection is available.

In terms of usage, ResultSet is preferred when we need to query large amounts of data, but do not require any updates or modifications. RowSet is useful when we need to manipulate data in various ways, such as sorting, filtering or updating, without an active database connection.

In summary, ResultSet provides read-only access to the database and works only when connected to the database, while RowSet provides more flexibility and can operate offline as well.

Types of ResultSet

ResultSet is a Java object which contains records retrieved from a database after executing an SQL query. There are three types of ResultSet:

  1. TYPE_FORWARD_ONLY: It is a default type of ResultSet which allows to traverse forward only. It does not allow scrolling in any direction.
  2. TYPE_SCROLL_INSENSITIVE: It allows to scroll in both the forward and backward directions. The changes made in the database are not reflected in the ResultSet.
  3. TYPE_SCROLL_SENSITIVE: It also allows to scroll in both the forward and backward directions. The changes made in the database are reflected in the ResultSet. This is useful when multiple users are accessing the same database at the same time.


ResultSet rs = statement.executeQuery("SELECT * FROM my_table");

ResultSet sensitiveResultSet = statement.executeQuery("SELECT * FROM my_table");

ResultSet insensitiveResultSet = statement.executeQuery("SELECT * FROM my_table");

Explanation of JDBC API Components

JDBC (Java Database Connectivity) is a Java API that enables accessing and manipulating various types of databases. The JDBC API consists of various components, which are explained below:

Driver Manager: It is a class that manages a list of database drivers. It matches connection requests from a java application with the proper database driver using communication subprotocols.

Driver: It is a Java software component that provides the communication between a java application and a database. It implements the JDBC API to interact with a specific type of database.

Connection: It is an interface that provides methods for connecting to a database, creating statements, and performing queries. A connection represents a session with the database.

Statement: It is an interface that provides methods for executing SQL statements and returning the results. It represents a static SQL statement that is executed by the database.

PreparedStatement: It is an interface that extends the Statement interface. It provides methods for executing precompiled SQL statements with parameters. It represents a precompiled SQL statement that is executed multiple times.

CallableStatement: It is an interface that extends the PreparedStatement interface. It provides methods for executing precompiled SQL statements that accept input and output parameters. It represents a stored procedure call.

ResultSet: It is an interface that provides methods for retrieving data from a database result set. It represents a set of rows returned by a SQL statement.

ResultSetMetaData: It is an interface that provides methods for retrieving metadata from a ResultSet object, such as column names.

DatabaseMetaData: It is an interface that provides methods for retrieving metadata from a database, such as database name, version, etc.

The components of the JDBC API provide developers with a standard way to interact with various databases using Java programming language. By using these components, developers can build database-driven applications in a robust and efficient manner.

Types of JDBC Statements

In JDBC, there are three types of statements that can be used to interact with a database:

  1. Statement: Used for executing a simple SQL statement without parameters.
  2. PreparedStatement: Used for executing a precompiled SQL statement that may contain one or more parameters.
  3. CallableStatement: Used for executing a database stored procedure.

Each type of statement has its own advantages and use cases depending on the requirements of the application. It is important to choose the appropriate statement type to achieve efficient and effective database interactions.

Explanation of JDBC batch processing

JDBC batch processing is a mechanism provided by Java to enable efficient execution of multiple SQL statements as a single batch, instead of sending each statement separately to the database server.

This is achieved by creating a batch object and adding multiple SQL statements to it using the addBatch() method. Once all statements are added, the executeBatch() method is called to execute the whole batch as a single unit.

Batch processing reduces the number of round-trips needed between the application and the database server, which improves performance. It also ensures the atomicity of the batch, which means that either all statements in the batch are executed, or none of them are.

Here's an example of using JDBC batch processing to insert multiple records into a database:

try {
   Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
   Statement stmt = conn.createStatement();

   String query1 = "INSERT INTO employees (id, name) VALUES (1, 'John')";
   String query2 = "INSERT INTO employees (id, name) VALUES (2, 'Jane')";
   String query3 = "INSERT INTO employees (id, name) VALUES (3, 'Bob')";

   // create a batch object

   // execute the batch
} catch (SQLException e) {

Difference between Statement and PreparedStatement

In Java, the Statement and PreparedStatement are used to execute SQL queries to interact with databases. The main differences between the two are:

- Compilation: The Statement is compiled every time the query is executed, while PreparedStatement is compiled only once, at the time of creation.

- Performance: Since PreparedStatement is compiled only once, it is faster than Statement for executing the same query multiple times.

- Prevention of SQL injection: PreparedStatement is more secure than Statement, as it allows parameterized queries which prevent SQL injection attacks.

- Flexibility: Statement is more flexible as compared to PreparedStatement as it allows dynamic queries to be built at run time. On the other hand, PreparedStatement is suitable for repetitive and fixed queries.

Therefore, PreparedStatement is preferred over Statement in most cases, as it provides better performance and security.

Explanation of DataSource in JDBC and its Benefits

In JDBC (Java Database Connectivity), DataSource is an interface that provides a connection to a database. It acts as a mediator between the application and the database. In general, a DataSource object provides connections to the database through its getConnection() method.

Some of the benefits of using DataSource are:

1. Connection Pooling - DataSource provides support for connection pooling. It means that a group of connections to the database is created at the time of initialization. When an application requests a connection to the database, it receives one from this pool. After the application is done with the connection, it puts it back into the pool, so it can be used by someone else.

2. Better Performance - Connection pooling helps improve performance by reducing the time needed to establish a connection to the database. It is because establishing a new connection to the database is a very time-consuming task.

3. Modular Code - DataSource makes it possible to write modular code. You can separate the code that deals with the database from the application code, so it can be managed independently.

4. Security - DataSource provides a way to configure database credentials in an external file, which can be kept confidential. Also, DataSource usually provides support for encryption of the password, so it is not exposed in plain text.

5. Maintainability - Since DataSource separates the code that deals with database connectivity from the application code, it is easier to maintain the system. Hence, it is beneficial from a maintenance point of view as well.


import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;

public class DatabaseConnection {
  static DataSource getDataSource() {
    // Creating a BasicDataSource object in order to connect to the database
    BasicDataSource dataSource = new BasicDataSource();
    // Setting the connection pool properties
    return dataSource;
  public static void main(String[] args) {
    // Getting the DataSource object
    DataSource dataSource = DatabaseConnection.getDataSource();
    try (Connection connection = dataSource.getConnection()) {
      // Perform database operations here
    } catch (SQLException e) {

In the above code, we are creating a BasicDataSource object, setting its properties, and returning it as a DataSource object. In the main() method, we are invoking getDataSource() method to get the DataSource object, and then setting up a database connection using the DataSource object.

Explanation of execute(), executeQuery(), and executeUpdate() methods in JDBC

In JDBC, execute(), executeQuery(), and executeUpdate() are three different methods used to execute SQL statements.



- This method is used to run any type of SQL statement (SELECT, INSERT, UPDATE, DELETE, etc.). It returns a boolean value, which is true if the result of the execution is a ResultSet object (i.e., a SELECT statement), and false otherwise.



- This method is used to execute SELECT statements that return a ResultSet object. It returns a ResultSet that contains the data produced by the SELECT statement.



- This method is used to execute SQL statements that do not return any data, such as INSERT, UPDATE, and DELETE statements. It returns an integer that represents the number of rows affected by the statement.

In summary, the main difference between these methods is the type of SQL statement they execute and the type of results they return. Developers need to use the correct method depending on their needs to execute SQL statements and retrieve the results efficiently.

Types of RowSet in JDBC

In JDBC, there are four types of RowSets available:

1. CachedRowSet: Stores data in memory and disconnected from the database. It allows modification and traversal of the data while disconnected and later can be connected again to synchronize changes with the database.

2. WebRowSet: It is similar to CachedRowSet but has additional features like it can be serialized and can work over the network.

3. FilteredRowSet: It acts as a filter over a CachedRowSet, allowing access to a subset of its rows based on a filter criteria.

4. JdbcRowSet: It is a connected row set, which is connected to the database throughout its life cycle. It doesn't need to be populated with data manually, as it gets its data directly from the database through a query. It can be used as a lightweight replacement for ResultSet.

Explanation of Getter and Setter Methods in ResultSet

In Java, the ResultSet interface provides methods to retrieve the data from a database. A Getter method is used to retrieve the values of object properties, while a Setter method is used to set the values of object properties. In a ResultSet, a Getter method is used to retrieve column values from the current row, and a Setter method is used set column values in the current row.

For example, the ResultSet interface provides a method called "getInt(int columnIndex)" to retrieve integer values from a column in the current row. Similarly, the "setInt(int columnIndex, int x)" method is used to set an integer value in a column in the current row.

Using Getter and Setter methods in ResultSet allows for easy manipulation of data within a database, as well as easy retrieval of data from a ResultSet object. It also ensures that the values being set or retrieved are of the correct data type and follows the desired format.

Understanding JDBC Locking System

In JDBC (Java Database Connectivity), a locking system is used to control concurrent access to a database. This means that when multiple users are trying to access the same data at the same time, the locking system ensures that only one user can modify the data while the others wait or are prevented from modifying it.

This is important for maintaining data integrity and preventing inconsistencies that may occur when multiple users attempt to modify the same data simultaneously. The JDBC locking system provides different levels of locking, such as row-level locking and table-level locking, which allow for more fine-tuned control over data access. By using JDBC's locking system, developers can ensure that their applications are able to handle multiple users accessing the same data without causing conflicts or compromising the integrity of the data.

Overview of Database Connection Pooling and Its Advantages

Database Connection Pooling is a technique used to improve performance in applications that repeatedly access a database. A connection pool is a cache of database connections maintained so that the connections are always ready to handle incoming requests from the application.

The advantages of database connection pooling include:

1. Improved Performance: Connection pooling reduces the overhead involved in establishing a new connection for every database request. By maintaining a pool of reusable connections, the application can respond to user requests quickly and efficiently.

2. Resource Optimization: Connection pooling minimizes the number of database connections needed to service client requests, freeing up resources in the database server for other tasks.

3. Scalability: Connection pooling helps an application scale efficiently by allowing it to make optimal use of available database connections.

4. Connection Reuse: Connection pooling reuses existing connections rather than creating new ones, reducing the overhead associated with managing and creating new connections.

In conclusion, database connection pooling is a valuable technique that can help improve application performance, optimize resource utilization, and enhance scalability.

Understanding Dirty Read in Databases

In database management systems, a dirty read occurs when one database transaction is allowed to read data from another transaction that is still in an uncommitted state. This means that the first transaction is reading data that has not yet been persisted and could potentially be rolled back. It can lead to inconsistencies in the data if the second transaction decides to not commit its changes. Therefore, it is considered a risk and should be avoided in database management systems.

Causes of "No Suitable Driver" Error

The "No Suitable Driver" error occurs when a Java application attempts to connect to a database using JDBC, but the necessary driver for that specific database is not installed or not being found in the classpath. This error can also occur when an incorrect URL is used to establish a connection to the database.

To resolve this error, ensure that the correct JDBC driver is installed and added to the classpath. Additionally, verify that the connection URL used by the application is accurate and properly configured.

// Sample code for establishing a connection
import java.sql.*;
public class DatabaseConnection {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost/myDatabase";
        String user = "root";
        String password = "password";

        try {
            Connection con = DriverManager.getConnection(url, user, password);
            Statement stmt = con.createStatement();
        } catch (SQLException e) {
            System.out.println("Error connecting to database: " + e.getMessage());

What is JDBC Connection and How to Get a JDBC Database Connection in Java

JDBC Connection is a feature of Java that allows communication with relational databases. It is used to access and manipulate data stored in a database using Java.

Here are the steps to establish a JDBC Database connection in a Java program:

1. Import the JDBC packages: Include the JDBC API packages in your Java program by using the import statement.

2. Load and register the JDBC driver: Before establishing the database connection, you need to load and register the JDBC driver using the Class.forName() method.

3. Create a Connection object: To establish a connection with the database, you need to create a Connection object with the help of the DriverManager.getConnection() method and specify the database URL, username, and password.

4. Create a Statement object: Once the connection is established, you need to create a Statement object using the Connection.createStatement() method.

5. Execute a query: After creating the statement object, you can use the executeQuery() method of the Statement object to execute queries and retrieve the data from the database.

6. Process data: Once the data is retrieved, you can process it in the Java program as per your requirements.

7. Close the connection: Finally, you need to close the database connection using the Connection.close() method to release the resources.

By following the above mentioned steps, you can get JDBC database connection in a simple Java program.

Using JDBC API to Call Stored Procedures

To call a stored procedure using JDBC API in Java, you can follow the below steps:

1. Import the required package:

import java.sql.*;

2. Load the JDBC driver using `Class.forName()`:


3. Create a connection to the database:

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

4. Create a CallableStatement object:

CallableStatement stmt = conn.prepareCall("{call procedure_name(?,?)}");

5. Set the input parameters of the stored procedure using `set` methods of the CallableStatement object:

stmt.setString(1, parameter1);
stmt.setString(2, parameter2);

6. Register the output parameters of the stored procedure using `registerOutParameter()` method of the CallableStatement object:

stmt.registerOutParameter(1, Types.INTEGER);

7. Execute the stored procedure using `execute()` method of the CallableStatement object:


8. Retrieve the output parameters of the stored procedure using `get` methods of the CallableStatement object:

int outputParam = stmt.getInt(1);

9. Close the CallableStatement and Connection objects:


The above steps can be modified and used based on the specific stored procedure and input/output parameters.

The Types of JDBC Architecture

There are two types of JDBC (Java Database Connectivity) architecture:

1. Two-tier JDBC architecture: In this type of architecture, the JDBC client interacts directly with the database server. The client handles both the application logic and the database connectivity.

2. Three-tier JDBC architecture: In this type of architecture, the JDBC client communicates with an intermediate server called the application server. The application server handles the application logic and forwards the database connectivity requests to the database server.

JDBC Transaction Management and its Importance

JDBC Transaction Management is a mechanism that manages the transaction process of a database. Transactions are a sequence of database operations that when executed, make sure that the database remains consistent and accurate.

JDBC Transaction Management is needed to ensure data integrity and reliability. For instance, if a transaction fails in the middle of a sequence of database operations, there is a risk of compromising data integrity. Therefore, to preserve the database's integrity, JDBC transaction management helps in performing the transaction process efficiently and ensures that all operations are complete or rolled back if necessary.

//Example of a JDBC transaction

Connection conn = null; try { conn = DriverManager.getConnection(DB_URL); conn.setAutoCommit(false); //turn off auto-commit Statement stmt = conn.createStatement(); stmt.executeUpdate("INSERT INTO Employee VALUES (101, 'John', 28)"); stmt.executeUpdate("UPDATE Employee SET AGE = 29 WHERE ID = 101"); conn.commit(); //commit if everything executes successfully } catch (SQLException e) { conn.rollback(); //rollback if something goes wrong } finally { conn.close(); //close the connection }

In this example, the auto-commit feature is disabled to manage the transaction manually. If both operations are successful, the transaction is committed, but if an exception occurs, the transaction is rolled back. By managing transactions efficiently, data integrity can be ensured, and consistency can be maintained.

Benefits of PreparedStatement over Statement

When working with databases in Java, using a PreparedStatement can provide several benefits over using a simple Statement.

A PreparedStatement allows for parameterized queries, which can help prevent SQL injection attacks and also improve performance by allowing the database to cache and reuse query execution plans. This can lead to significant performance improvements if the same query is executed multiple times with different parameter values.

In addition, using a PreparedStatement can also make your code more readable and maintainable by separating the query from the parameter values. This can make it easier to debug and modify your code in the future.

Overall, while using a Statement may be simpler in some cases, using a PreparedStatement can provide significant benefits in terms of performance, security, and maintainability.

Transaction Management Methods in JDBC

In JDBC, there are two methods available for transaction management:



: This method is used to commit the current transaction. It makes all the changes made in the transaction permanent and releases all the locks and resources held by the transaction.



: This method is used to rollback the current transaction. It cancels all the changes made in the transaction and releases all the locks and resources held by the transaction.

These methods can be used with the


interface to manage transactions in JDBC. It is important to manage transactions properly in order to ensure data integrity and consistency.

Most Common Exceptions in JDBC with Examples:

Some of the most common exceptions in JDBC are:

1. SQLException: This is the most frequently occurring exception in JDBC as it is thrown when there is a problem with accessing the database. Example:
try {
     // code to access database
} catch (SQLException e) {

2. ClassNotFoundException: This exception is thrown when the JDBC driver class is not found in the classpath. Example:
try {
} catch (ClassNotFoundException e) {

3. BatchUpdateException: This exception is thrown when there is an error in the batch operation that was being performed. Example:
try {
     // code for batch operation
} catch (BatchUpdateException e) {

What is Two-Phase Commit in JDBC?

Two-Phase Commit is a protocol that ensures that a transaction is completed successfully across multiple systems. In the context of JDBC, it is used to ensure that a transaction involving multiple databases is either committed or rolled back in a coordinated way. This protocol involves two phases: prepare and commit. During the prepare phase, each database involved in the transaction verifies that it can commit the transaction and prepares to do so. During the commit phase, each database either commits or rolls back the transaction. If any database fails to commit the transaction, all the other databases involved in the transaction are also rolled back to maintain transaction consistency. The two-phase commit protocol ensures that all databases coordinated in the transaction are in a consistent state after the transaction.

Isolation Levels for JDBC Connections

What are the different isolation levels available for JDBC connections?

Connection con = DriverManager.getConnection(jdbcUrl, jdbcUsername, jdbcPassword);
con.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); // set isolation level

The available isolation levels are:

  • TRANSACTION_NONE: No transaction isolation. This level is available only in auto-commit mode
  • TRANSACTION_READ_UNCOMMITTED: Transactions can read uncommitted changes made by concurrent transactions
  • TRANSACTION_READ_COMMITTED: Transactions cannot read uncommitted changes made by concurrent transactions. This is the default level
  • TRANSACTION_REPEATABLE_READ: Transactions can read changes made by concurrent transactions but not changes made after the current transaction started
  • TRANSACTION_SERIALIZABLE: Transactions cannot read or modify data that has been modified by concurrent transactions until those transactions are completed

Creating a Table Dynamically in a JDBC Application

To create a table dynamically in a JDBC application, follow these steps:

  1. Establish a database connection using JDBC.
  2. Create a statement object.
  3. Execute a SQL query to create a table dynamically. The query will specify table name, columns, and data types.
  4. Close the statement object and the connection.

Below is an example code snippet that demonstrates how to create a table dynamically:

import java.sql.*;

public class CreateTable { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/EMP"; static final String USER = "username"; static final String PASS = "password";

public static void main(String[] args) { Connection conn = null; Statement stmt = null; String tableName = "CUSTOMERS"; try { Class.forName("com.mysql.jdbc.Driver");

System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS);

System.out.println("Creating table..."); stmt = conn.createStatement();

String sql = "CREATE TABLE " + tableName + " " + "(id INTEGER not NULL, " + " first VARCHAR(255), " + " last VARCHAR(255), " + " age INTEGER, " + " PRIMARY KEY ( id ))";

stmt.executeUpdate(sql); System.out.println("Table " + tableName + " created successfully..."); } catch(SQLException se) { se.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } finally { try { if(stmt!=null) stmt.close(); } catch(SQLException se2) { } try { if(conn!=null) conn.close(); } catch(SQLException se){ se.printStackTrace(); } } System.out.println("Goodbye!"); } }

Note that this code uses MySQL database for demo purposes. You will need to modify the code to match your database configuration.

Technical Interview Guides

Here are guides for technical interviews, categorized from introductory to advanced levels.

View All

Best MCQ

As part of their written examination, numerous tech companies necessitate candidates to complete multiple-choice questions (MCQs) assessing their technical aptitude.

View MCQ's
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.