Card 05/ 08
Bridge in the Wild: JDBC Drivers
Your code talks to Connection and Statement; each database supplies the driver behind them.
JDBC, Java's database API, is a Bridge between the code that queries a database and the drivers that talk to each database. Application code is written against the interfaces in java.sql, such as Connection and PreparedStatement, and each database vendor ships a driver with its own classes behind them. The same query code runs on PostgreSQL, MySQL or an in-memory database by changing the URL.
| Template | JDBC |
|---|---|
| Abstraction | Your data-access code, such as countOrders, which holds a Connection |
| RefinedAbstraction | Other data-access classes, each a variant on the same side |
| Implementor | The java.sql interfaces: Connection, PreparedStatement, ResultSet |
| ConcreteImplementor | A vendor driver's classes, such as PostgreSQL's connection class |
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BrJdbc {
static int countOrders(Connection connection, String customer) throws SQLException {
String sql = "SELECT COUNT(*) FROM orders WHERE customer = ?";
try (PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setString(1, customer);
try (ResultSet rows = statement.executeQuery()) {
rows.next();
return rows.getInt(1);
}
}
}
public static void main(String[] args) {
System.out.println("drivers registered: " + DriverManager.drivers().count());
String url = "jdbc:postgresql://localhost/shop";
try (Connection connection = DriverManager.getConnection(url)) {
System.out.println("orders: " + countOrders(connection, "ana"));
} catch (SQLException error) {
System.out.println("SQLException: " + error.getMessage());
}
}
}drivers registered: 0
SQLException: No suitable driver found for jdbc:postgresql://localhost/shopThe listing ran in eclipse-temurin:21-jdk with no driver on the class path and no database. DriverManager found no registered driver able to handle a jdbc:postgresql: URL and refused, which shows where the bridge is crossed: the code chose nothing but a URL, and the driver behind it is found when the program runs. With PostgreSQL's driver added, the same code would return the count without a line changed.
countOrders never names a vendor class, which is what lets both sides vary. Drivers are rewritten and new databases are added without touching application code, and new data-access code is written without touching any driver.
← → move through sections and cards