Java Academy

Master Java Development

Menu

Core Java

Servlets

JDBC

Microservices

Build Tools

APIs

JDBC · Lesson 2

JDBC Architecture and Drivers

What JDBC Provides

JDBC is the standard Java API for communicating with relational databases. It defines interfaces for connections, statements, results, and transactions while database vendors supply driver implementations. This separation lets application code use a consistent programming model across supported databases.

JDBC Layers

An application uses JDBC interfaces, a driver translates those calls into a database protocol, and the database executes the SQL. The DriverManager is suitable for simple examples, while a DataSource is preferred for managed applications.

import java.sql.Connection;
import java.sql.DriverManager;

public class DriverConnectionDemo {
    public static void main(String[] arguments) throws Exception {
        String databaseUrl = "jdbc:h2:mem:academy";
        try (Connection connection = DriverManager.getConnection(databaseUrl, "sa", "")) {
            System.out.println("Connected: " + !connection.isClosed());
            System.out.println("Database: " + connection.getMetaData().getDatabaseProductName());
        }
    }
}

Driver and API Comparison

ComponentResponsibilityExample
JDBC APICommon Java interfacesConnection, ResultSet
DriverTranslates JDBC callsPostgreSQL JDBC driver
DriverManagerFinds and opens driversSimple command-line app
DataSourceManaged connection factoryWeb application and pool

Common Mistake and Practices

Common Mistake: Treating the JDBC driver as optional runtime configuration. The application may compile successfully but fail when it first tries to connect if the driver is absent from the runtime classpath.

  • Keep the driver dependency in the runtime build.
  • Use a DataSource for server applications.
  • Keep credentials outside source code.
  • Close connections with try-with-resources.
  • Verify driver and database version compatibility.

Real-World Use Case

A reporting service uses the same JDBC interfaces in local tests and production, changing only the driver and connection configuration. The repository code remains focused on queries rather than vendor-specific socket details.

Quiz Check

Quick Knowledge Test

Loading quiz questions...