Skip to content

JDBC (Java Database Connectivity) in Java

JDBC (Java Database Connectivity) is an API that allows Java applications to connect to databases and execute SQL queries. It provides a standard interface for connecting to relational databases and interacting with them using SQL. JDBC simplifies database interaction in Java by abstracting the complexities involved in establishing connections and executing SQL commands.

The JDBC API is part of the java.sql package, which includes classes and interfaces to interact with various relational database systems (e.g., MySQL, Oracle, PostgreSQL, etc.).


Key Components of JDBC

  1. Driver Manager: Manages a list of database drivers. It is responsible for establishing a connection with the database.
  2. Driver: A class that implements the java.sql.Driver interface and knows how to connect to a specific database.
  3. Connection: An interface that provides methods for creating and managing SQL statements, as well as for managing transactions.
  4. Statement: Used to execute SQL queries.
  5. PreparedStatement: A subclass of Statement that allows you to execute precompiled SQL queries.
  6. ResultSet: Represents the result of a query. It contains the data retrieved from the database.
  7. SQLException: Handles database-related exceptions.

Steps for Working with JDBC

  1. Load the Database Driver: Load the appropriate driver for the database.
  2. Establish a Connection: Use DriverManager.getConnection() to create a connection to the database.
  3. Create a Statement: Use Connection.createStatement() or Connection.prepareStatement() to create a statement object for executing SQL queries.
  4. Execute SQL Queries: Use methods like executeQuery() for SELECT statements or executeUpdate() for INSERT, UPDATE, and DELETE statements.
  5. Process the Result Set: If the query returns data, process the ResultSet object.
  6. Close the Resources: Close the Connection, Statement, and ResultSet objects to avoid resource leaks.

Example: JDBC with MySQL

Assuming you have MySQL installed and running, here’s a simple example that demonstrates how to connect to a MySQL database, execute a query, and display the result.


1. JDBC Setup

You need to add the JDBC driver for your database (e.g., MySQL Connector/J for MySQL) to your project classpath. For MySQL, you can download the driver from MySQL official website or include it via Maven as follows:

xml
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.23</version>
</dependency>

2. Example of Basic JDBC Operations

Connecting to the Database and Executing Queries
java
import java.sql.*;

public class JDBCExample {
    public static void main(String[] args) {
        // Database credentials
        String url = "jdbc:mysql://localhost:3306/mydatabase";  // URL to connect to the database
        String user = "root";  // Database username
        String password = "password";  // Database password

        // SQL query
        String query = "SELECT * FROM employees";  // Query to retrieve data

        // Establishing the connection
        try (Connection conn = DriverManager.getConnection(url, user, password);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(query)) {

            // Process the result set
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String position = rs.getString("position");
                System.out.println("ID: " + id + ", Name: " + name + ", Position: " + position);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Explanation of the Code:

  1. Database Connection:

    • DriverManager.getConnection(): Establishes a connection to the database using the provided URL, username, and password.
  2. Statement Creation:

    • Connection.createStatement(): Creates a Statement object for executing SQL queries.
  3. Executing Queries:

    • Statement.executeQuery(): Executes a SELECT query and returns the result as a ResultSet.
  4. Processing the ResultSet:

    • ResultSet.next(): Iterates through the result set. Each call to next() moves to the next row.
    • ResultSet.getXXX(): Retrieves the values of the columns. Here, getInt("id"), getString("name"), and getString("position") are used to fetch the data.
  5. Resource Management:

    • Try-with-resources: Automatically closes the resources (Connection, Statement, ResultSet) when the try block finishes, ensuring proper resource management.

3. Using PreparedStatement for Insert/Update/Delete

A PreparedStatement is used when you need to execute SQL queries multiple times, especially for parameterized queries (to prevent SQL injection attacks).

Example of PreparedStatement (INSERT):

java
import java.sql.*;

public class PreparedStatementExample {
    public static void main(String[] args) {
        // Database credentials
        String url = "jdbc:mysql://localhost:3306/mydatabase"; 
        String user = "root"; 
        String password = "password"; 

        // SQL query
        String insertQuery = "INSERT INTO employees (name, position) VALUES (?, ?)";

        // Establishing the connection
        try (Connection conn = DriverManager.getConnection(url, user, password);
             PreparedStatement stmt = conn.prepareStatement(insertQuery)) {

            // Set parameters
            stmt.setString(1, "John Doe");
            stmt.setString(2, "Manager");

            // Execute the insert query
            int rowsAffected = stmt.executeUpdate();
            System.out.println("Rows inserted: " + rowsAffected);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Explanation of the Code:

  • PreparedStatement:

    • prepareStatement(): Precompiles the SQL query for efficiency.
    • setXXX(): Sets the values of the query parameters. Here, setString(1, "John Doe") sets the first parameter to "John Doe".
  • Executing the Query:

    • executeUpdate(): Executes the SQL update (INSERT, UPDATE, DELETE). It returns the number of rows affected.

4. Handling Transactions in JDBC

JDBC allows you to control transactions, so you can commit or roll back changes to the database.

Example of Managing Transactions:

java
import java.sql.*;

public class TransactionExample {
    public static void main(String[] args) {
        // Database credentials
        String url = "jdbc:mysql://localhost:3306/mydatabase";
        String user = "root";
        String password = "password";

        // SQL queries
        String updateQuery1 = "UPDATE employees SET position = 'Senior Developer' WHERE id = 1";
        String updateQuery2 = "UPDATE employees SET position = 'Senior Developer' WHERE id = 2";

        // Establishing the connection
        try (Connection conn = DriverManager.getConnection(url, user, password);
             Statement stmt = conn.createStatement()) {

            // Turn off auto-commit for transaction management
            conn.setAutoCommit(false);

            // Execute the first update query
            stmt.executeUpdate(updateQuery1);

            // Execute the second update query
            stmt.executeUpdate(updateQuery2);

            // Commit the transaction
            conn.commit();
            System.out.println("Transaction committed successfully.");

        } catch (SQLException e) {
            try {
                // Rollback in case of error
                if (conn != null) {
                    conn.rollback();
                    System.out.println("Transaction rolled back.");
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }
    }
}

Explanation of the Code:

  • Transaction Management:
    • setAutoCommit(false): Disables the auto-commit mode, so all changes made in the transaction are not committed automatically.
    • commit(): Commits the transaction, making all changes permanent.
    • rollback(): Rolls back the transaction in case of an error, undoing any changes made during the transaction.

5. Closing Resources

In JDBC, it's important to close database connections, statements, and result sets to avoid resource leaks.

Best Practice for Closing Resources:

java
try (Connection conn = DriverManager.getConnection(url, user, password);
     Statement stmt = conn.createStatement();
     ResultSet rs = stmt.executeQuery(query)) {

    // Process ResultSet...
} catch (SQLException e) {
    e.printStackTrace();
}
  • Try-with-resources: Automatically closes Connection, Statement, and ResultSet objects when they go out of scope.

Conclusion

JDBC is a powerful API in Java for interacting with relational databases. Here's a summary of the main steps:

  1. Connecting to a database using DriverManager.getConnection().
  2. Creating statements with Statement or PreparedStatement.
  3. Executing queries using executeQuery() for SELECT and executeUpdate() for INSERT, UPDATE, DELETE.
  4. Handling results using ResultSet.
  5. Managing transactions with commit() and rollback().
  6. Closing resources properly using try-with-resources.

JDBC is essential for building database-driven applications in Java, providing robust features for working with relational databases.

J2J Institute private limited