Java : DriverManager (JDBC) con ejemplos

DriverManager (Java SE 22 & JDK 22) en Java con ejemplos.
Encontrará ejemplos de código en la mayoría de los métodos de DriverManager.

Nota :


Summary

El servicio básico para gestionar un conjunto de controladores JDBC. (Traducción automática)

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)

Elimina el controlador especificado de la lista de controladores registrados de DriverManager. (Traducción automática)

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 ()

Recupera una secuencia con todos los controladores JDBC actualmente cargados a los que tiene acceso la persona que llama actualmente. (Traducción automática)

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)

Intenta establecer una conexión a la URL de la base de datos proporcionada. (Traducción automática)

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)

Intenta establecer una conexión a la URL de la base de datos proporcionada. (Traducción automática)

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)

Intenta establecer una conexión a la URL de la base de datos proporcionada. (Traducción automática)

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)

Intenta localizar un controlador que comprenda la URL proporcionada. (Traducción automática)

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 ()

Recupera una enumeración con todos los controladores JDBC actualmente cargados a los que tiene acceso la persona que llama actualmente. (Traducción automática)

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 ()

Obtiene el tiempo máximo en segundos que un controlador puede esperar al intentar iniciar sesión en una base de datos. (Traducción automática)

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 ()

Obsoleto. Utilice getLogWriter (Traducción automática)

Deprecated.

static PrintWriter getLogWriter ()

Recupera el escritor de registros. (Traducción automática)

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)

Imprime un mensaje en el flujo de registro JDBC actual. (Traducción automática)

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)

Registra el controlador dado con DriverManager. (Traducción automática)

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)

Registra el controlador dado con DriverManager. (Traducción automática)

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)

Establece el tiempo máximo en segundos que esperará un conductor mientras intenta conectarse a una base de datos una vez que se ha identificado al conductor. (Traducción automática)

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)

Obsoleto. Utilice setLogWriter (Traducción automática)

Deprecated.

static void setLogWriter (PrintWriter out)

Establece el objeto PrintWriter de registro/rastreo que utilizan DriverManager y todos los controladores. (Traducción automática)

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