Skip to lesson

What JDBC is: API and driver

A shop's Java program must read products and save orders in a database, but the shop may run MySQL today and PostgreSQL next year. How can one Java program talk to many databases without being rewritten?

The problem: one Java program, many database products

JDBC (Java Database Connectivity) is the standard way for a Java program to talk to a relational database. It has two halves: the JDBC API that ships with the JDK, and a driver from the database vendor.

Try three database URLs with only the JDK on the classpath and see what Java does.

Example 1 · Only the JDK: no driver, no connection

NoDriverDemo.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;
public class NoDriverDemo {    public static void main(String[] args) {        System.out.println("Drivers on the classpath: " + DriverManager.drivers().count());
        String[] urls = {            "jdbc:mysql://localhost:3306/shoplite",            "jdbc:postgresql://localhost:5432/shoplite",            "jdbc:oracle:thin:@localhost:1521/XEPDB1"        };        for (String url : urls) {            try (Connection conn = DriverManager.getConnection(url, "shoplite_app", "secret")) {                System.out.println("Connected to " + url);            } catch (SQLException e) {                System.out.println(e.getMessage());            }        }    }}
Output
Drivers on the classpath: 0
No suitable driver found for jdbc:mysql://localhost:3306/shoplite
No suitable driver found for jdbc:postgresql://localhost:5432/shoplite
No suitable driver found for jdbc:oracle:thin:@localhost:1521/XEPDB1

What this code does

  • DriverManager.drivers() lists the drivers Java has found. With the plain JDK the count is 0.
  • Each getConnection call fails with SQLException: No suitable driver found for <url>: no loaded driver claims a jdbc:mysql:, jdbc:postgresql: or jdbc:oracle: URL.

Each database product, such as MySQL, PostgreSQL or Oracle, listens on the network and expects requests in its own protocol: the exact format of the bytes a client sends. Without a standard, a Java program would carry separate code for each product and be rewritten when a college project moved from one to another. With JDBC, the program calls the same Java methods and a product-specific library does the talking.

The JDK has the standard but no library that knows MySQL, which is why all three calls fail.

The JDBC API in java.sql: Connection, Statement and ResultSet

The JDBC API is the set of interfaces and classes in the java.sql package that every JDK includes, such as Connection, Statement and ResultSet. Your code is written against these types, never against a vendor's classes.

Ask Java which of the main JDBC types are interfaces and which are ordinary classes.

Example 2 · The JDBC API is mostly interfaces

JdbcApiDemo.javaJava
import java.sql.Connection;import java.sql.Driver;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class JdbcApiDemo {    public static void main(String[] args) {        Class<?>[] types = {            Connection.class, Statement.class, PreparedStatement.class,            ResultSet.class, Driver.class, DriverManager.class, SQLException.class        };        for (Class<?> type : types) {            String kind = type.isInterface() ? "interface" : "class";            System.out.printf("%-18s %-10s in %s%n", type.getSimpleName(), kind, type.getPackageName());        }    }}
Output
Connection         interface  in java.sql
Statement          interface  in java.sql
PreparedStatement  interface  in java.sql
ResultSet          interface  in java.sql
Driver             interface  in java.sql
DriverManager      class      in java.sql
SQLException       class      in java.sql

What this code does

  • Connection, Statement, PreparedStatement, ResultSet and Driver are interfaces in java.sql: the JDK defines the methods, a driver supplies the code.
  • DriverManager and SQLException are ordinary classes with real code, so they work even before any driver is loaded.

Your program uses only these types and never names a MySQL class, so the same code can run against another product with a different library and URL. The types you meet most:

  • Connection: one open, logged-in session with a database.
  • Statement: carries one SQL command to the database over a connection.
  • ResultSet: the rows a SELECT sends back, read one row at a time.
  • DriverManager (a class) picks a driver and opens a Connection; SQLException (a class) reports what went wrong.

Predict the output

Interface or class?

Read the program, then pick what it prints.

Two of the main JDBC types are checked with isInterface().

import java.sql.Connection;
import java.sql.DriverManager;
public class KindCheck {
public static void main(String[] args) {
System.out.println(Connection.class.isInterface() + " " + DriverManager.class.isInterface());
}
}

The driver: a vendor library that implements those interfaces

A JDBC driver is a JAR file from the database vendor that contains the real classes behind the JDBC interfaces for one product. For MySQL it is MySQL Connector/J, published as mysql-connector-j.

Two toy drivers, one for MySQL and one for PostgreSQL, show how a URL finds its driver.

Three layers. Your Java code uses the java.sql interfaces Connection, Statement and ResultSet. The JDBC driver, mysql-connector-j, implements them and talks the MySQL protocol over TCP to the MySQL server on port 3306. Swap the driver and the URL; the Java code stays the same.

Example 3 · How DriverManager picks a driver by URL (toy model)

ToyDriverDemo.javaJava
import java.sql.Connection;import java.sql.Driver;import java.sql.DriverManager;import java.sql.DriverPropertyInfo;import java.sql.SQLException;import java.util.Properties;import java.util.logging.Logger;
class ToyDriver implements Driver {    private final String prefix;
    ToyDriver(String prefix) {        this.prefix = prefix;    }
    @Override    public boolean acceptsURL(String url) {        return url.startsWith(prefix);    }
    @Override    public Connection connect(String url, Properties info) throws SQLException {        if (!acceptsURL(url)) {            return null;        }        throw new SQLException("Toy driver for " + prefix + " cannot really connect");    }
    @Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) { return new DriverPropertyInfo[0]; }    @Override public int getMajorVersion() { return 1; }    @Override public int getMinorVersion() { return 0; }    @Override public boolean jdbcCompliant() { return false; }    @Override public Logger getParentLogger() { return Logger.getGlobal(); }
    @Override    public String toString() {        return "ToyDriver(" + prefix + ")";    }}
public class ToyDriverDemo {    public static void main(String[] args) throws SQLException {        DriverManager.registerDriver(new ToyDriver("jdbc:mysql:"));        DriverManager.registerDriver(new ToyDriver("jdbc:postgresql:"));
        String[] urls = {            "jdbc:mysql://localhost:3306/shoplite",            "jdbc:postgresql://localhost:5432/shoplite",            "jdbc:sqlserver://localhost:1433"        };        for (String url : urls) {            try {                System.out.println(url + " -> " + DriverManager.getDriver(url));            } catch (SQLException e) {                System.out.println(url + " -> " + e.getMessage());            }        }
        try {            DriverManager.getConnection(urls[0], "shoplite_app", "secret");        } catch (SQLException e) {            System.out.println("getConnection: " + e.getMessage());        }    }}
Output
jdbc:mysql://localhost:3306/shoplite -> ToyDriver(jdbc:mysql:)
jdbc:postgresql://localhost:5432/shoplite -> ToyDriver(jdbc:postgresql:)
jdbc:sqlserver://localhost:1433 -> No suitable driver
getConnection: Toy driver for jdbc:mysql: cannot really connect

What this code does

  • A real driver also opens the connection. Returning null from connect means "not my URL", so DriverManager asks the next driver.
  • Each ToyDriver says yes in acceptsURL only for its own prefix. DriverManager.getDriver(url) returns the first registered driver that accepts the URL.
  • No driver accepts jdbc:sqlserver:, so DriverManager throws No suitable driver. getConnection with a MySQL URL reaches the toy MySQL driver's connect, which throws its own message.

Every driver implements the java.sql.Driver interface. DriverManager keeps a list of loaded drivers and asks each one: "Is this URL yours?". The mysql in jdbc:mysql://... is what the MySQL driver looks for.

This split is why switching a project from MySQL to PostgreSQL changes the driver dependency and the URL, while most Java code stays the same. The SQL itself may still need small changes, because each product has its own SQL extras.

Example 3 is a simplified model: real drivers also open the network connection, log in and run SQL. The way DriverManager chooses a driver by URL is the same.

The path of a query: Java code, driver, network, MySQL server and back

When your code calls a JDBC method, the work passes through several layers. Knowing them tells you where to look when something fails.

  1. Your code calls an interface method, such as executeQuery("SELECT VERSION()") on a Statement.
  2. The driver's class behind that interface turns the call into a MySQL protocol message.
  3. The message travels over a TCP connection (a two-way network channel) to the server, by default on port 3306.
  4. The MySQL server checks your rights, runs the SQL and sends the rows back over the same connection.
  5. The driver turns those bytes into a ResultSet object, and your code reads it.

Example 4 · src/main/java/com/shoplite/app/WhoAnswers.java

Runs in: the shoplite-console Maven project with the MySQL driver and the ShopLite database

WhoAnswers.javaJava
package com.shoplite.app;
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class WhoAnswers {    public static void main(String[] args) throws SQLException {        String url = System.getenv("DB_URL");        String user = System.getenv("DB_USER");        String password = System.getenv("DB_PASSWORD");
        try (Connection conn = DriverManager.getConnection(url, user, password)) {            // Your variable has the interface type; the object comes from the driver            System.out.println("Variable type:  java.sql.Connection");            System.out.println("Object class:   " + conn.getClass().getName());
            // This SQL travels over the network to the server, and the answer comes back            try (Statement st = conn.createStatement();                 ResultSet rs = st.executeQuery("SELECT VERSION(), CURRENT_USER(), DATABASE()")) {                rs.next();                System.out.println("Server version: " + rs.getString(1));                System.out.println("Logged in as:   " + rs.getString(2));                System.out.println("Database:       " + rs.getString(3));            }        }    }}
Sample output
Variable type:  java.sql.Connection
Object class:   com.mysql.cj.jdbc.ConnectionImpl
Server version: 8.4.6
Logged in as:   shoplite_app@localhost
Database:       shoplite

What this code does

  • The variable is declared as java.sql.Connection, but the object inside is com.mysql.cj.jdbc.ConnectionImpl, a class from the MySQL driver.
  • SELECT VERSION(), CURRENT_USER(), DATABASE() is answered by the server, not by Java: the version, the logged-in user and the current database all come back over the network.

The four steps every JDBC program follows

Every JDBC program, from a homework exercise to a large backend, follows the same four steps. Example 5 runs them in order.

Example 5 · src/main/java/com/shoplite/app/CountProducts.java

Runs in: the shoplite-console Maven project with the MySQL driver and the ShopLite database

CountProducts.javaJava
package com.shoplite.app;
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class CountProducts {    public static void main(String[] args) throws SQLException {        String url = System.getenv("DB_URL");        String user = System.getenv("DB_USER");        String password = System.getenv("DB_PASSWORD");
        // Step 1: connect        try (Connection conn = DriverManager.getConnection(url, user, password);             // Step 2: send SQL             Statement st = conn.createStatement();             ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM products")) {
            // Step 3: read the result            rs.next();            System.out.println("Products in ShopLite: " + rs.getInt(1));        }    }}
Output
Products in ShopLite: 15

What this code does

  • Step 1 opens the connection, step 2 sends SELECT COUNT(*) FROM products, and step 3 moves to the single result row and reads its first column with getInt(1).
  • Step 4 is the closing brace: try-with-resources closes the ResultSet, then the Statement, then the Connection, in the reverse order of opening.
  • The URL, user and password come from environment variables. The Keeping Credentials lesson explains why; until then, set them as that lesson shows or read along.

Closing matters because a connection holds memory and a slot on the server until it is closed. Try-with-resources, from the Try-with-Resources in Depth module, closes everything for you even when an exception happens.

This module covers step 1. The Running Queries with JDBC module covers steps 2 and 3, and the Resource Handling & SQL Errors module covers step 4 in depth.

Order of execution

The four steps of a JDBC program

Tap the steps in the order a JDBC program does them.

try (Connection conn = DriverManager.getConnection(url, user, password);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM products")) {
rs.next();
System.out.println(rs.getInt(1));
}
Examples 4 and 5 run inside the shoplite-console project once the driver is added, which is the next lesson. Read them now for the shape; you will run them soon.

Next step

Check your understanding

11 quick questions