広告

Java : Driver (JDBC) - API使用例

Driver (Java SE 22 & JDK 22) の使い方まとめです。
だいたいのメソッドを網羅済みです。
API仕様書のおともにどうぞ。


概要

すべてのドライバ・クラスが実装しなければならないインタフェースです。

クラス構成

Driver は、JDBCのドライバを表すインタフェースです。

補足

  • JDBCのドライバには Apache Derby を使っています。
    Apache Derby は、古い JDK に含まれていたこともありましたが、最新の 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());

// 結果
// ↓
//-- 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);
            }
        }
    }

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

メソッド

boolean acceptsURL (String url)

指定されたURLに接続できるとドライバが判断するかどうかを取得します。

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)

指定された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 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);
            }
        }
    }

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

int getMajorVersion ()

ドライバのメジャー・バージョン番号を取得します。

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

int getMinorVersion ()

ドライバのマイナー・バージョンを取得します。

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

Logger getParentLogger ()

このドライバで使用されるすべてのロガーの親ロガーを返します。

// Apache Derby はロガーをサポートしていないようです。
try {
    final var driver = DriverManager.getDriver("jdbc:derby:");
    final var logger = driver.getParentLogger();
} catch (SQLFeatureNotSupportedException e) {
    System.out.println("SQLFeatureNotSupportedException! : " + e.getMessage());
}

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

DriverPropertyInfo[] getPropertyInfo (String url, Properties info)

このドライバの有効なプロパティについての情報を取得します。

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);
}

// 結果
// ↓
//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 ()

このドライバが正規のJDBC準拠ドライバかどうかを報告します。

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

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

関連記事

ページの先頭へ