Java Database Connectivity (JDBC)


Java Database Connectivity (JDBC)

JDBC (Java Database Connectivity) is a Java API that facilitates communication between applications and databases. It offers methods for establishing connections, executing SQL queries, and performing operations such as retrieving, updating, and deleting data. JDBC serves as a link between Java applications and different database systems.


Key Steps in JDBC

1. Load the JDBC Driver

The driver serves as a bridge, enabling the application to connect to the database.

Syntax:

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

Example: For MySQL, the driver class name is com.mysql.cj.jdbc.Driver.

2. Establish a Connection

The DriverManager class is used to establish a connection with the database.

Syntax:

Connection conn = DriverManager.getConnection("jdbc:mysql://hostname:port/dbname", "username", "password");

Example:

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/employees", "root", "password");

3. Create a Statement Object

A Statement object allows execution of SQL queries.

Syntax:

Statement stmt = conn.createStatement();

4. Execute SQL Queries

Use executeQuery for SELECT statements and executeUpdate for INSERT, UPDATE, or DELETE operations.

Syntax:

ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
int rowsAffected = stmt.executeUpdate("INSERT INTO employees (id, name) VALUES (1, 'John')");

5. Process the Results

Use the ResultSet object to process query results.

Syntax:

while (rs.next()) {
    int id = rs.getInt("id");
    String name = rs.getString("name");
    System.out.println("ID: " + id + ", Name: " + name);
}

6. Close Resources

Always close Connection, Statement, and ResultSet to free resources.

Syntax:

rs.close();
stmt.close();
conn.close();

Complete Example

Here’s a simple program to connect to a MySQL database, query data, and print results:

import java.sql.*;

public class JdbcExample {
    public static void main(String[] args) {
        String jdbcURL = "jdbc:mysql://localhost:3306/employees";
        String username = "root";
        String password = "password";

        try {
            // Load the MySQL JDBC driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Establish a database connection
            Connection conn = DriverManager.getConnection(jdbcURL, username, password);
            System.out.println("Connected to the database!");

            // Create a statement
            Statement stmt = conn.createStatement();

            // Execute a SQL query
            String sql = "SELECT * FROM employees";
            ResultSet rs = stmt.executeQuery(sql);

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

            // Close resources
            rs.close();
            stmt.close();
            conn.close();
            System.out.println("Connection closed!");

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

Core Classes and Interfaces in JDBC

  • DriverManager: Manages the database drivers and establishes connections.
  • Connection: Represents the link between the application and the database.
  • Statement: Executes SQL queries.
  • PreparedStatement: Executes precompiled SQL statements with parameters for improved performance and security.
  • CallableStatement: Executes stored procedures in the database.
  • ResultSet: Retrieves the results of a query.

Advantages of JDBC

  • Database independence due to a standard interface.
  • Integration with a variety of relational databases (MySQL, Oracle, PostgreSQL, etc.).
  • Offers powerful features for transaction management and error handling.

Understanding JDBC enables developers to interact efficiently with databases in Java applications.

PreviousNext