Java : Driver (JDBC) con ejemplos

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

Nota :


Summary

La interfaz que cada clase de controlador debe implementar. (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.
final var driver = DriverManager.getDriver("jdbc:derby:");

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
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 protocol = "jdbc:derby:";
final var driver = DriverManager.getDriver(protocol);

final var url = protocol + "memory:db";
final var properties = new Properties();
properties.setProperty("create", "true");

try (final var connection = driver.connect(url, properties)) {

    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

boolean acceptsURL (String url)

Recupera si el controlador cree que puede abrir una conexión a la URL determinada. (Traducción automática)

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

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

final var ret = driver.acceptsURL(url);
System.out.println(ret); // true
final var driver = DriverManager.getDriver("jdbc:derby:");

final var ret = driver.acceptsURL("abc");
System.out.println(ret); // false

Connection connect (String url, Properties info)

Intenta establecer una conexión de base de datos a la URL 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 protocol = "jdbc:derby:";
final var driver = DriverManager.getDriver(protocol);

final var url = protocol + "memory:db";
final var properties = new Properties();
properties.setProperty("create", "true");

try (final var connection = driver.connect(url, properties)) {

    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
}

int getMajorVersion ()

Recupera el número de versión principal del controlador. (Traducción automática)

final var driver = DriverManager.getDriver("jdbc:derby:");
System.out.println(driver.getMajorVersion()); // 10
System.out.println(driver.getMinorVersion()); // 17

int getMinorVersion ()

Obtiene el número de versión secundaria del controlador. (Traducción automática)

final var driver = DriverManager.getDriver("jdbc:derby:");
System.out.println(driver.getMajorVersion()); // 10
System.out.println(driver.getMinorVersion()); // 17

Logger getParentLogger ()

Devuelve el registrador principal de todos los registradores utilizados por este controlador. (Traducción automática)

// Apache Derby doesn't seem to support the Logger.
try {
    final var driver = DriverManager.getDriver("jdbc:derby:");
    final var logger = driver.getParentLogger();
} catch (SQLFeatureNotSupportedException e) {
    System.out.println("SQLFeatureNotSupportedException! : " + e.getMessage());
}

// Result
// ↓
//SQLFeatureNotSupportedException! : Feature not implemented: getParentLogger().

DriverPropertyInfo[] getPropertyInfo (String url, Properties info)

Obtiene información sobre las posibles propiedades de este controlador. (Traducción automática)

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

final var values = driver.getPropertyInfo(protocol, new Properties());
for (final var value : values) {
    System.out.println(value.name + " : " + value.description);
}

// Result
// ↓
//databaseName : Database identity
//encryptionProvider : Cryptographic service provider
//encryptionAlgorithm : Cryptographic algorithm
//encryptionKeyLength : Cryptographic key length
//encryptionKey : External cryptographic key
//territory : Locale for the database
//collation : Collation for character datatypes
//user : User name
//logDevice : Log directory path
//rollForwardRecoveryFrom : Backup path for roll-forward recovery
//createFrom : Backup path for creating database from backup
//restoreFrom : Backup path for restoring database from backup
//bootPassword : Secret cryptographic key
//password : User password
//shutdown : Shut down Derby
//deregister : Deregister AutoloadedDriver
//create : Create database
//dataEncryption : Encrypt database on disk
//upgrade : Upgrade database
final var protocol = "jdbc:derby:";
final var driver = DriverManager.getDriver(protocol);

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

final var values = driver.getPropertyInfo(protocol, info);
System.out.println(values.length); // 0

boolean jdbcCompliant ()

Informa si este controlador es un controlador compatible con JDBC genuino. (Traducción automática)

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

final var ret = driver.jdbcCompliant();
System.out.println(ret); // true

Related posts

To top of page