JDBC

jdbc1JdbcOverview

Path
pkg11jdbc/jdbc1JdbcOverview.java
Package
pkg11jdbc
Study order
1
Run
Single-file source launch
Command
java pkg11jdbc/jdbc1JdbcOverview.java
Dependencies
Optional in-memory JDBC driver (H2, SQLite, or HSQLDB)
Lesson
Back to the chapter

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg11jdbc/jdbc1JdbcOverview.java
1package pkg11jdbc;2 3import java.sql.Driver;4import java.sql.DriverManager;5import java.util.Enumeration;6 7/*8 * jdbc1JdbcOverview.java9 * ----------------------10 * JDBC (Java Database Connectivity): the standard API for relational databases.11 *12 * DEFINITION:13 *   JDBC is a vendor-neutral API (java.sql) for connecting to SQL databases,14 *   running statements, and reading results. Each database ships a "driver" jar15 *   that implements the API for its wire protocol.16 *17 * THE 5 STEPS:18 *   1. (Java 6+) Driver auto-loads from the classpath via the ServiceLoader.19 *   2. Connection conn = DriverManager.getConnection(url, user, pass);20 *   3. Statement / PreparedStatement to send SQL.21 *   4. ResultSet to read rows back.22 *   5. close() everything (use try-with-resources).23 *24 * JDBC URL FORMAT:  jdbc:<subprotocol>:<subname>25 *   jdbc:postgresql://localhost:5432/mydb26 *   jdbc:mysql://localhost:3306/mydb27 *   jdbc:sqlite:app.db                (file)   |   jdbc:h2:mem:test (in-memory)28 *29 * NOTE: This repo has no external jars, so no driver is registered by default.30 *       Add one (e.g. sqlite-jdbc.jar) and run:31 *       java -cp ".;sqlite-jdbc.jar" pkg11jdbc/jdbc1JdbcOverview.java32 */33public class jdbc1JdbcOverview {34 35    public static void main(String[] args) {36        System.out.println("Registered JDBC drivers on the classpath:");37        Enumeration<Driver> drivers = DriverManager.getDrivers();38        int count = 0;39        while (drivers.hasMoreElements()) {40            Driver d = drivers.nextElement();41            System.out.printf("  - %s (v%d.%d)%n",42                    d.getClass().getName(), d.getMajorVersion(), d.getMinorVersion());43            count++;44        }45        if (count == 0) {46            System.out.println("  (none) — add a driver jar to the classpath to connect.");47        }48 49        System.out.println("\nExample JDBC URLs:");50        for (String url : new String[]{51                "jdbc:postgresql://localhost:5432/shop",52                "jdbc:mysql://localhost:3306/shop",53                "jdbc:sqlite:shop.db",54                "jdbc:h2:mem:shop"}) {55            System.out.println("  " + url);56        }57 58        System.out.println("\nThe canonical try-with-resources pattern:");59        System.out.println("""60              try (Connection c = DriverManager.getConnection(url, user, pass);61                   PreparedStatement ps = c.prepareStatement("SELECT * FROM users WHERE id = ?")) {62                  ps.setInt(1, 42);63                  try (ResultSet rs = ps.executeQuery()) {64                      while (rs.next()) System.out.println(rs.getString("name"));65                  }66              }""");67    }68}