Java : DriverManager (JDBC) with Examples

DriverManager (Java SE 22 & JDK 22) with Examples.
You will find code examples on most DriverManager methods.


Summary

The basic service for managing a set of JDBC drivers.

Class diagram

Note :

  • The code examples in this page use Apache Derby as the JDBC driver. Apache Derby was once included in older JDKs, but is not included in the latest JDK.
DriverManager.drivers().forEach(driver -> {
    System.out.println("-- driver --");
    System.out.println("package : " + driver.getClass().getPackage().getName());
    System.out.println("major version : " + driver.getMajorVersion());
    System.out.println("minor version : " + driver.getMinorVersion());
});

// Result
// ↓
//-- driver --
//package : org.apache.derby.iapi.jdbc
//major version : 10
//minor version : 17
//-- driver --
//package : org.apache.derby.client
//major version : 10
//minor version : 17
record Product(String name, int stock) {
}

final var products = List.of(
        new Product("Orange", 10),
        new Product("Banana", 20),
        new Product("Apple", 30)
);

final var url = "jdbc:derby:memory:db;create=true";
try (final var connection = DriverManager.getConnection(url)) {

    System.out.println("-- create table --");
    try (final var statement = connection.createStatement()) {
        final var ret = statement.executeUpdate("""
                CREATE TABLE PRODUCTS (
                    NAME VARCHAR(20),
                    STOCK INTEGER
                )
                """);
        System.out.println("ret = " + ret);
    }

    System.out.println("-- insert --");
    try (final var statement = connection.prepareStatement("""
            INSERT INTO PRODUCTS VALUES( ?, ? )
            """)) {
        for (final var product : products) {
            statement.setString(1, product.name());
            statement.setInt(2, product.stock());
            final var ret = statement.executeUpdate();
            System.out.println("ret = " + ret);
        }
    }

    System.out.println("-- select --");
    try (final var statement = connection.createStatement()) {
        try (final var result = statement.executeQuery("""
                SELECT * FROM PRODUCTS
                """)) {
            while (result.next()) {
                final var name = result.getString("name");
                final var stock = result.getInt("stock");

                System.out.println(name + " : " + stock);
            }
        }
    }

    // Result
    // ↓
    //-- create table --
    //ret = 0
    //-- insert --
    //ret = 1
    //ret = 1
    //ret = 1
    //-- select --
    //Orange : 10
    //Banana : 20
    //Apple : 30
}

Methods

static void deregisterDriver (Driver driver)

Removes the specified driver from the DriverManager's list of registered drivers.

final var url = "jdbc:derby:";
final var derby = DriverManager.getDriver(url);

// package org.apache.derby.iapi.jdbc
System.out.println(derby.getClass().getPackage());

System.out.println("-- drivers --");
DriverManager.drivers().forEach(driver -> {
    System.out.println("package : " + driver.getClass().getPackage().getName());
});

// Result
// ↓
//-- drivers --
//package : org.apache.derby.iapi.jdbc
//package : org.apache.derby.client

DriverManager.deregisterDriver(derby);

System.out.println("-- drivers --");
DriverManager.drivers().forEach(driver -> {
    System.out.println("package : " + driver.getClass().getPackage().getName());
});

// Result
// ↓
//-- drivers --
//package : org.apache.derby.client

DriverManager.registerDriver(derby);

System.out.println("-- drivers --");
DriverManager.drivers().forEach(driver -> {
    System.out.println("package : " + driver.getClass().getPackage().getName());
});

// Result
// ↓
//-- drivers --
//package : org.apache.derby.client
//package : org.apache.derby.iapi.jdbc

static Stream<Driver> drivers ()

Retrieves a Stream with all of the currently loaded JDBC drivers to which the current caller has access.

DriverManager.drivers().forEach(driver -> {
    System.out.println("-- driver --");
    System.out.println("package : " + driver.getClass().getPackage().getName());
    System.out.println("major version : " + driver.getMajorVersion());
    System.out.println("minor version : " + driver.getMinorVersion());
});

// Result
// ↓
//-- driver --
//package : org.apache.derby.iapi.jdbc
//major version : 10
//minor version : 17
//-- driver --
//package : org.apache.derby.client
//major version : 10
//minor version : 17

static Connection getConnection (String url)

Attempts to establish a connection to the given database URL.

record Product(String name, int stock) {
}

final var products = List.of(
        new Product("Orange", 10),
        new Product("Banana", 20),
        new Product("Apple", 30)
);

final var url = "jdbc:derby:memory:db;create=true";
try (final var connection = DriverManager.getConnection(url)) {

    System.out.println("-- create table --");
    try (final var statement = connection.createStatement()) {
        final var ret = statement.executeUpdate("""
                CREATE TABLE PRODUCTS (
                    NAME VARCHAR(20),
                    STOCK INTEGER
                )
                """);
        System.out.println("ret = " + ret);
    }

    System.out.println("-- insert --");
    try (final var statement = connection.prepareStatement("""
            INSERT INTO PRODUCTS VALUES( ?, ? )
            """)) {
        for (final var product : products) {
            statement.setString(1, product.name());
            statement.setInt(2, product.stock());
            final var ret = statement.executeUpdate();
            System.out.println("ret = " + ret);
        }
    }

    System.out.println("-- select --");
    try (final var statement = connection.createStatement()) {
        try (final var result = statement.executeQuery("""
                SELECT * FROM PRODUCTS
                """)) {
            while (result.next()) {
                final var name = result.getString("name");
                final var stock = result.getInt("stock");

                System.out.println(name + " : " + stock);
            }
        }
    }

    // Result
    // ↓
    //-- create table --
    //ret = 0
    //-- insert --
    //ret = 1
    //ret = 1
    //ret = 1
    //-- select --
    //Orange : 10
    //Banana : 20
    //Apple : 30
}

static Connection getConnection (String url, String user, String password)

Attempts to establish a connection to the given database URL.

final var protocol = "jdbc:derby:";
final var path = Path.of("R:", "java-work", "db");
final var url = protocol + path + ";create=true";
System.out.println(url); // jdbc:derby:R:\java-work\db;create=true

try (final var connection = DriverManager.getConnection(url + ";user=AAA")) {
    try (final var statement = connection.prepareCall("""
            CALL SYSCS_UTIL.SYSCS_CREATE_USER(?, ?)
            """)) {
        statement.setString(1, "AAA"); // user
        statement.setString(2, "XYZ"); // password
        statement.execute();
    }
}

System.out.println("-- shutdown --");
try {
    DriverManager.getConnection(url + ";shutdown=true");
} catch (SQLException e) {
    System.out.println(e.getMessage());
}

// Result
// ↓
//-- shutdown --
//Database 'R:\java-work\db' shutdown.

System.out.println("-- invalid password --");
try (final var connection = DriverManager.getConnection(url, "AAA", "123")) {
    System.out.println("Connected!");
} catch (SQLException e) {
    System.out.println("SQLException! : " + e.getMessage());
}

// Result
// ↓
//-- invalid password --
//SQLException! : Connection authentication failure occurred.
// Reason: Invalid authentication..

System.out.println("-- valid password --");
try (final var connection = DriverManager.getConnection(url, "AAA", "XYZ")) {
    System.out.println("Connected!");
} catch (SQLException e) {
    System.out.println("SQLException! : " + e.getMessage());
}

// Result
// ↓
//-- valid password --
//Connected!

static Connection getConnection (String url, Properties info)

Attempts to establish a connection to the given database URL.

final var url = "jdbc:derby:memory:db";

try (final var connection = DriverManager.getConnection(url)) {
    System.out.println("Connected!");
} catch (SQLException e) {
    System.out.println("SQLException! : " + e.getMessage());
}

// Result
// ↓
//SQLException! : Database 'memory:db' not found.

final var info = new Properties();
info.setProperty("create", "true");

try (final var connection = DriverManager.getConnection(url, info)) {
    System.out.println("Connected!");
} catch (SQLException e) {
    System.out.println("SQLException! : " + e.getMessage());
}

// Result
// ↓
//Connected!

static Driver getDriver (String url)

Attempts to locate a driver that understands the given URL.

final var url = "jdbc:derby:";
final var driver = DriverManager.getDriver(url);

System.out.println("package : " + driver.getClass().getPackage().getName());
System.out.println("major version : " + driver.getMajorVersion());
System.out.println("minor version : " + driver.getMinorVersion());

// Result
// ↓
//package : org.apache.derby.iapi.jdbc
//major version : 10
//minor version : 17

static Enumeration<Driver> getDrivers ()

Retrieves an Enumeration with all of the currently loaded JDBC drivers to which the current caller has access.

final var drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
    final var driver = drivers.nextElement();

    System.out.println("-- driver --");
    System.out.println("package : " + driver.getClass().getPackage().getName());
    System.out.println("major version : " + driver.getMajorVersion());
    System.out.println("minor version : " + driver.getMinorVersion());
}

// Result
// ↓
//-- driver --
//package : org.apache.derby.iapi.jdbc
//major version : 10
//minor version : 17
//-- driver --
//package : org.apache.derby.client
//major version : 10
//minor version : 17

static int getLoginTimeout ()

Gets the maximum time in seconds that a driver can wait when attempting to log in to a database.

final var ret1 = DriverManager.getLoginTimeout();
System.out.println(ret1); // 0

DriverManager.setLoginTimeout(60);

final var ret2 = DriverManager.getLoginTimeout();
System.out.println(ret2); // 60

static PrintStream getLogStream ()

Deprecated. Use getLogWriter

Deprecated.

static PrintWriter getLogWriter ()

Retrieves the log writer.

try (final var writer = new PrintWriter(new StringWriter())) {

    final var ret1 = DriverManager.getLogWriter();
    System.out.println(ret1); // null

    DriverManager.setLogWriter(writer);

    final var ret2 = DriverManager.getLogWriter();
    System.out.println(ret2 == writer); // true
}

static void println (String message)

Prints a message to the current JDBC log stream.

final var sw = new StringWriter();
try (final var writer = new PrintWriter(sw)) {

    DriverManager.setLogWriter(writer);

    final var driver = DriverManager.getDriver("jdbc:derby:");

    DriverManager.println("");
    DriverManager.println("** println **");
    DriverManager.println("  package : " + driver.getClass().getPackage().getName());
}

System.out.println("-- writer --");
System.out.print(sw);

// Result
// ↓
//-- writer --
//DriverManager.getDriver("jdbc:derby:")
//registerDriver: org.apache.derby.iapi.jdbc.AutoloadedDriver@18317edc
//registerDriver: org.apache.derby.client.ClientAutoloadedDriver@1f760b47
//DriverManager.initialize: jdbc.drivers = null
//JDBC DriverManager initialized
//getDriver returning org.apache.derby.iapi.jdbc.AutoloadedDriver
//
//** println **
//  package : org.apache.derby.iapi.jdbc

static void registerDriver (Driver driver)

Registers the given driver with the DriverManager.

final var url = "jdbc:derby:";
final var derby = DriverManager.getDriver(url);

// package org.apache.derby.iapi.jdbc
System.out.println(derby.getClass().getPackage());

System.out.println("-- drivers --");
DriverManager.drivers().forEach(driver -> {
    System.out.println("package : " + driver.getClass().getPackage().getName());
});

// Result
// ↓
//-- drivers --
//package : org.apache.derby.iapi.jdbc
//package : org.apache.derby.client

DriverManager.deregisterDriver(derby);

System.out.println("-- drivers --");
DriverManager.drivers().forEach(driver -> {
    System.out.println("package : " + driver.getClass().getPackage().getName());
});

// Result
// ↓
//-- drivers --
//package : org.apache.derby.client

DriverManager.registerDriver(derby);

System.out.println("-- drivers --");
DriverManager.drivers().forEach(driver -> {
    System.out.println("package : " + driver.getClass().getPackage().getName());
});

// Result
// ↓
//-- drivers --
//package : org.apache.derby.client
//package : org.apache.derby.iapi.jdbc

static void registerDriver (Driver driver, DriverAction da)

Registers the given driver with the DriverManager.

final var url = "jdbc:derby:";
final var derby = DriverManager.getDriver(url);

// package org.apache.derby.iapi.jdbc
System.out.println(derby.getClass().getPackage());

DriverManager.deregisterDriver(derby);

System.out.println("-- registerDriver --");
DriverManager.registerDriver(derby, () -> {
    System.out.println("Deregister!");
});

System.out.println("-- deregisterDriver --");
DriverManager.deregisterDriver(derby);

// Result
// ↓
//-- registerDriver --
//-- deregisterDriver --
//Deregister!

static void setLoginTimeout (int seconds)

Sets the maximum time in seconds that a driver will wait while attempting to connect to a database once the driver has been identified.

final var ret1 = DriverManager.getLoginTimeout();
System.out.println(ret1); // 0

DriverManager.setLoginTimeout(60);

final var ret2 = DriverManager.getLoginTimeout();
System.out.println(ret2); // 60

static void setLogStream (PrintStream out)

Deprecated. Use setLogWriter

Deprecated.

static void setLogWriter (PrintWriter out)

Sets the logging/tracing PrintWriter object that is used by the DriverManager and all drivers.

final var sw = new StringWriter();
try (final var writer = new PrintWriter(sw)) {

    DriverManager.setLogWriter(writer);

    final var driver = DriverManager.getDriver("jdbc:derby:");

    DriverManager.println("");
    DriverManager.println("** println **");
    DriverManager.println("  package : " + driver.getClass().getPackage().getName());
}

System.out.println("-- writer --");
System.out.print(sw);

// Result
// ↓
//-- writer --
//DriverManager.getDriver("jdbc:derby:")
//registerDriver: org.apache.derby.iapi.jdbc.AutoloadedDriver@18317edc
//registerDriver: org.apache.derby.client.ClientAutoloadedDriver@1f760b47
//DriverManager.initialize: jdbc.drivers = null
//JDBC DriverManager initialized
//getDriver returning org.apache.derby.iapi.jdbc.AutoloadedDriver
//
//** println **
//  package : org.apache.derby.iapi.jdbc

Related posts

To top of page