what is java database connectivity jdbc

What is JDBC (Java Database Connectivity)

May 11th, 2026
4773
5:00 Minutes

Imagine a programming language or API that allows a seamless connection between different relational database systems. This is exactly what Java database connectivity (JDBC) is used for. It connects to a variety of relational database management systems (RDBMS) like MySQL, PostgreSQL, Oracle and more. But how does it do that?

Well it is an API that empowers developers to couple, query and handle data across multiple sources with extensive efficiency and simplicity. Continue to explore this article and understand what is Java Database Connectivity, its architecture, components and steps to establish JDBC. It also provides a glance on the classes and interfaces used in this connectivity, along with a simple example to create a JDBC application.

What is Java Database Connectivity?

what is java database connectivity

JDBC is a Java API that helps to connect and interact Java applications with databases. It provides a standardized way for Java code to access and manipulate data stored in relational database management systems and other data sources. It was originally developed by Sun Microsystems (acquired by Oracle in 2010) in 1997 with Java Development Kit (JDK) 1.1.

JDBC allows developers to establish connections with data sources, execute SQL queries and process result sets effectively. Think of it as a translator between databases and Java applications. A particular JDBC application capable of accessing numerous data sources regardless of its Java Virtual Machine (JVM). as a result, it provides unprecedented flexibility and portability.

Explore igmGuru's Java Course program to learn Java from Industry experts.

The Architecture of Java Database Connectivity

database connectivity layer

Let's come to the point of discussion: How does it do it? To understand it better, one must explore the JDBC architecture and its underlying components. It is a multilayer architecture, which includes the following layers:

1. Java Application Layer:

This is where the Java program resides that uses the JDBC API to interact with the database.

2. JDBC API Layer:

This layer provides interfaces and classes that enable Java applications to interact with databases. Key interfaces include:

  • Connection: Create a connection with the database.
  • Statement: Executes SQL queries.
  • ResultSet: Retrieves data from the database.
  • PreparedStatement: Executes parameterized SQL queries.
  • DriverManager: Manages JDBC drivers.

3. JDBC Driver Manager Layer:

This layer is responsible for loading and managing JDBC drivers. It acts as a central component for finding and loading the appropriate driver to connect to a specific database.

4. JDBC Driver Layer:

Each database system has its own JDBC driver, which is a piece of software that handles the actual communication with the database. It also translates JDBC API calls into database-specified commands.

5. Database Layer:

This is where the data resides and it is the actual database system that the Java application is interacting with.

Architecture Models of Java Database Connectivity

Further, this architecture follows a two-tier and three-tier model for processing. Their working is described below:

1. Two-Tier Architecture

In this architecture model, the application directly communicates with the required database using JDBC driver. It involves sending queries to that database and then sending the result back to the application. To understand it better, imagine a client/server setup. Here the system acts like a client that directly communicates with one of the remote database servers. Its structure will look like this:

Client Application (Java) -> JDBC Driver -> Database

2. Three-Tier Architecture

This architecture model involves sending the user queries to the middle-tier service. Now the service will interact with the database. In essence, results of the database are processed and then shared with the user by the middle tier. It's sure to look like this:

Client Application -> Application Server -> JDBC Driver -> Database

Related Article- What are Packages in Java? A Comprehensive Guide

Components of Java Database Connectivity

JDBC components play a crucial role in interacting with a database. There are mainly five types of components in JDBC, including:

  • Driver: It is the interface responsible for controlling communication with database servers. It also helps to extract information related to the driver objects.
  • Driver Manager: This is responsible for managing an essential set of JDBC drivers.
  • Connection: It is referred to as a session or interface that collects all the methods required to integrate any database.
  • Statements: It is responsible for carrying out a static SQL statement.
  • ResultSet: It is responsible for accessing the result row-by-row.

Classes and Interfaces of Java Database Connectivity

Classes and interfaces are also among the most crucial elements to establish Java database connectivity. Here's a table outlining the essential JDBC classes and interfaces:

Class/Interface Description
DriverManager It manages a set of JDBC drivers and is the most used way to establish a connection to a database.
Connection It portrays a session with a specified database. All SQL statements are executed within the context of a connection.
Statement It is used for executing static SQL statements and returning the results produced by them.
PreparedStatement It is more efficient for executing the same statement multiple times and provides protection against SQL injection attacks.
CallableStatement It extends PreparedStatement and is used to execute stored procedures in the database.
ResultSet It represents a table of data generated by executing a SQL query. It provides methods to navigate through the rows and retrieve column values.
ResultSetMetaData It provides information about the columns in a ResultSet object, such as the number of columns, column names, data types, etc.
DatabaseMetaData It provides information about the database as a whole, including supported SQL, database product name and version, driver name and version and information about tables, procedures and functions.
SQLException It is an exception that provides information on a database access error or other errors.
SQLWarning It is a warning that provides information on a database access warning. Warnings are silently chained to the object whose method produced it.

Steps to Establish Database Connection Using JDBC

In this section, we will implement all the above knowledge to establish a database connection using JDBC. It involves the following five steps:

1. Register the Driver Class

Start with registering a driver class, which is a Java class that will implement a JDBC API of the database. The driver class is responsible for managing the communication between the Java application and database. It is necessary to load and register the driver class before establishing the connection.

Class.forName("com.mysql.jdbc.Driver")

2. Create the Connection

Once you register the driver class, continue with creating the connection. Here you will need to use a connection object that represents a session between both ends. This allows a seamless SQL statements sharing and results retrieval. This will require some specific details like username, database URL and password.

String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "myuser";
String password = "mypassword";

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

3. Create a Statement

Now you have to create a statement object. It will update statements and enable SQL queries against the database. Creating a statement involves using the createStatement() method. This method is provided by the Connection object.

Statement statement = connection.createStatement();

4. Execute Queries

The next step is to execute queries. JDBC supports a variety of queries including INSERT, SELECT, DELETE and UPDATE. Executing them will allow modifying the existing data and retrieving data from the database. It is done by using the method provided by the same Statement object.

String query = "SELECT * FROM customers";
ResultSet resultSet = statement.executeQuery(query);

while (resultSet.next()) {
    String name = resultSet.getString("name");
    int age = resultSet.getInt("age");
    System.out.println("Name: " + name + ", Age: " + age);
}

5. Close Connection

It is also important to close the connection after the purpose of the connection is achieved. It releases the data sources and ensures complete cleanup. Closing the connection also helps to free up system resources and avoid potential memory leaks.

resultSet.close();
statement.close();
connection.close();

How to Create a JDBC Application? Explained With Example

This Java program demonstrates how to connect to a PostgreSQL database using JDBC and execute a SELECT query to retrieve data.

// Java program to implement a simple JDBC application for PostgreSQL SELECT
import java.sql.*;

public class PostgreSQLDataFetcher {
    public static void main(String[] args) {

        // Database URL, username, and password for PostgreSQL
        // Replace with your PostgreSQL database name, host, and port if different
        String url = "jdbc:postgresql://localhost:5432/your_database_name";
        // Replace with your PostgreSQL username
        String username = "your_username";
        // Replace with your PostgreSQL password
        String password = "your_password";

        // SQL query to select all data from a 'users' table
        // Make sure you have a table named 'users' with 'id' and 'name' columns in your database
        String query = "SELECT id, name FROM users";

        // Declare Connection, Statement, and ResultSet outside try-catch
        // so they can be closed in the finally block
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            // Step 1: Load the PostgreSQL JDBC Driver
            // The Class.forName() method dynamically loads the JDBC driver class.
            // This driver class is typically found in the PostgreSQL JDBC JAR file.
            Class.forName("org.postgresql.Driver");
            System.out.println("PostgreSQL JDBC Driver registered!");

            // Step 2: Establish the connection to the database
            // DriverManager.getConnection() attempts to establish a connection
            // to the database identified by the given URL.
            connection = DriverManager.getConnection(url, username, password);
            System.out.println("Connection established successfully.");

            // Step 3: Create a Statement object
            // A Statement object is used for executing SQL queries.
            statement = connection.createStatement();

            // Step 4: Execute the SELECT query
            // executeQuery() is used for SQL SELECT statements.
            // It returns a ResultSet object containing the data produced by the query.
            resultSet = statement.executeQuery(query);
            System.out.println("\n--- Data from 'users' table ---");

            // Step 5: Process the ResultSet
            // The ResultSet contains all the rows that satisfy the WHERE clause of the SQL query.
            // resultSet.next() moves the cursor to the next row and returns true if there is one.
            if (!resultSet.isBeforeFirst()) { // Check if there are any rows
                System.out.println("No data found in 'users' table.");
            } else {
                while (resultSet.next()) {
                    // Retrieve column values by their column name or index
                    int id = resultSet.getInt("id"); // Get integer value from 'id' column
                    String name = resultSet.getString("name"); // Get string value from 'name' column
                    System.out.println("ID: " + id + ", Name: " + name);
                }
            }

        } catch (ClassNotFoundException e) {
            // Handle case where the JDBC driver is not found
            System.err.println("JDBC Driver not found. Please ensure the PostgreSQL JDBC JAR is in your classpath.");
            System.err.println("Error: " + e.getMessage());

        } catch (SQLException e) {
            // Handle SQL-related errors
            System.err.println("SQL Error occurred.");
            System.err.println("SQL State: " + e.getSQLState());
            System.err.println("Error Code: " + e.getErrorCode());
            System.err.println("Message: " + e.getMessage());

        } finally {
            // Step 6: Close JDBC objects in reverse order of creation to release resources
            // Always close in a finally block to ensure they are closed even if an exception occurs.
            try {
                if (resultSet != null) {
                    resultSet.close();
                    System.out.println("ResultSet closed.");
                }
                if (statement != null) {
                    statement.close();
                    System.out.println("Statement closed.");
                }
                if (connection != null) {
                    connection.close();
                    System.out.println("Connection closed.");
                }
            } catch (SQLException e) {
                System.err.println("Error closing JDBC objects: " + e.getMessage());
            }
        }
    }
}

Output:

PostgreSQL JDBC Driver registered!
Connection established successfully.
--- Data from 'users' table ---
ID: 1, Name: Alice
ID: 2, Name: Bob
ID: 3, Name: Charlie
ResultSet closed.
Statement closed.
Connection closed.

Master Java Programming with Our Java Tutorial

Boost your coding skills and gain hands-on knowledge in Java.

Explore Now
Java Learning Illustration

Wrapping Up - What is Java Database Connectivity

This article has explained Java database connectivity, its architecture, components and classes and interface, along with practical examples. It is a complete demonstration of how you can use this feature to connect different database systems to your Java application. Continue to learn more about this programming language with our Java tutorial to become an expert.

Related Articles

FAQs

Q1. What is the purpose of database connectivity?

The main purpose of database connectivity is to enable clients to interact with different databases from a particular application. With this connection, they can send commands to get answers in the form of a result set.

Q2. What is the importance of JDBC in Java?

It provides developers with a standardized way for their applications to interact with databases. This enables them to connect, query and manipulate data without requiring creating complicated codes.

Q3. What is Java Database Connectivity used for?

JDBC provides a standardized way for Java programs to establish a connection with various relational database management systems (RDBMS) like MySQL, Oracle, PostgreSQL, SQL Server, and more.

  • Executing SQL Queries
  • Processing Result Sets
  • Managing Transactions
  • Providing Database Agnosticism

Q4. Which database systems can be connected through JDBC?

It can connect most of the relational database management systems including MySQL, Oracle, PostgreSQL, Microsoft SQL Server, IBM DB2, MariaDB, Derby, HSQLDB, Sybase, etc.

Q5. Is JDBC easy for beginners?

Yes, JDBC is easy to learn. Basic knowledge of Java and SQL is enough to get started.

Course Schedule

Course NameBatch TypeDetails
Java TrainingEvery WeekdayView Details
Java TrainingEvery WeekendView Details
About the Author
Author Nehal Sharma
About the Author

Nehal Sharma is a skilled content writer with expertise in Java, mobile development, and data analytics. She transforms complex data into actionable insights and has experience in business intelligence, data science, and Salesforce. She also simplifies technical concepts into clear, engaging content for learners and professionals.

Drop Us a Query
Fields marked * are mandatory
×

Your Shopping Cart


Your shopping cart is empty.