JDBC (Java Database Connectivity) is a Java API that enables Java applications to interact with relational databases. It provides a standard way to execute SQL statements and retrieve data.

Key Components of JDBC

JDBC relies on several core classes and interfaces:

  • Driver: Manages the connection to the database (e.g., MySQL, PostgreSQL).
  • Connection: Represents a connection to a specific database.
  • Statement: Executes SQL queries and updates.
  • ResultSet: Stores the data returned from a database query.
  • PreparedStatement: Used for precompiled SQL statements to prevent SQL injection.

Steps to Use JDBC

  1. Add JDBC Driver
    Include the appropriate JDBC driver JAR (e.g., mysql-connector-java) in your project.
    💡 Example: For MySQL, use com.mysql.cj.jdbc.Driver.

  2. Load the Driver
    Register the driver with the DriverManager class.

    Class.forName("com.mysql.cj.jdbc.Driver");
    
  3. Establish a Connection
    Use DriverManager.getConnection() to connect to the database.
    🔗 Example:

    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
    
  4. Execute SQL Queries
    Create a Statement or PreparedStatement to run SQL commands.
    📜 Example:

    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT * FROM users");
    
  5. Process Results
    Iterate through ResultSet to extract data.
    📌 Example:

    while (rs.next()) {
        int id = rs.getInt("id");
        String name = rs.getString("name");
    }
    
  6. Close Resources
    Always close ResultSet, Statement, and Connection to avoid leaks.
    🧹 Use try-with-resources for automatic cleanup:

    try (Connection conn = ...) {
        // Code here
    }
    

Best Practices

✅ Use PreparedStatement for dynamic queries.
✅ Implement connection pooling for performance.
✅ Handle exceptions properly and close resources in finally blocks.
✅ Avoid hardcoding database credentials in production code.

Expand Your Knowledge

For a deeper dive into database connections in Java, check out our Java Database Connections Guide.

JDBC Architecture
JDBC Components