Java : Connection (JDBC) with Examples

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


Summary

A connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection.

Class diagram

public record Product(String name, int stock) {
    @Override
    public String toString() {
        return "%s(%d)".formatted(name, 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
}

Code examples on this page use the helper classes below.

public record Product(String name, int stock) {
    @Override
    public String toString() {
        return "%s(%d)".formatted(name, stock);
    }
}
public class ProductTable {

    public void create(Connection connection) throws SQLException {
        try (final var statement = connection.createStatement()) {
            statement.executeUpdate("""
                    CREATE TABLE PRODUCTS (
                        NAME VARCHAR(20),
                        STOCK INTEGER
                    )
                    """);
        }
    }

    public void insert(Connection connection, Product product) throws SQLException {
        insert(connection, List.of(product));
    }

    public void insert(Connection connection, List<Product> products) throws SQLException {
        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());
                statement.executeUpdate();
            }
        }
    }

    public void update(Connection connection, Product product) throws SQLException {
        try (final var statement = connection.prepareStatement("""
                UPDATE PRODUCTS SET STOCK = ? WHERE NAME = ?
                """)) {
            statement.setInt(1, product.stock());
            statement.setString(2, product.name());
            statement.executeUpdate();
        }
    }

    public List<Product> selectAll(Connection connection) throws SQLException {
        final var products = new ArrayList<Product>();
        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");
                    products.add(new Product(name, stock));
                }
            }
        }

        return products;
    }
}

Fields

static final int TRANSACTION_NONE

A constant indicating that transactions are not supported.

System.out.println(Connection.TRANSACTION_NONE); // 0

Derby does not support this field.

final var url = "jdbc:derby:memory:db;create=true";
try (final var connection = DriverManager.getConnection(url)) {
    connection.setTransactionIsolation(Connection.TRANSACTION_NONE);
} catch (SQLException e) {
    System.out.println(e);
}

// Result
// ↓
//java.sql.SQLException: Invalid or (currently) unsupported isolation level, '0',
//  passed to Connection.setTransactionIsolation().
//  The currently supported values are java.sql.Connection.TRANSACTION_SERIALIZABLE,
//  java.sql.Connection.TRANSACTION_REPEATABLE_READ,
//  java.sql.Connection.TRANSACTION_READ_COMMITTED,
//  and java.sql.Connection.TRANSACTION_READ_UNCOMMITTED.

static final int TRANSACTION_READ_COMMITTED

A constant indicating that dirty reads are prevented; non-repeatable reads and phantom reads can occur.

System.out.println(Connection.TRANSACTION_READ_COMMITTED); // 2
// An example for occurring non-repeatable reads.
final var url = "jdbc:derby:memory:db;create=true";
final var table = new ProductTable();

final var product1 = new Product("Orange", 10);
final var product2 = new Product("Orange", 9999);

// Prepares a table.
try (final var connection = DriverManager.getConnection(url)) {
    table.create(connection);
    table.insert(connection, product1);
}

try (final var executor = Executors.newFixedThreadPool(2)) {
    executor.submit(() -> {
        try (final var connectionA = DriverManager.getConnection(url)) {

            connectionA.setTransactionIsolation(
                    Connection.TRANSACTION_READ_COMMITTED);
            connectionA.setAutoCommit(false);

            System.out.println("A : select all : " + table.selectAll(connectionA));

            System.out.println("A : sleep ... (5 sec.)");
            TimeUnit.SECONDS.sleep(5);

            System.out.println("A : select all : " + table.selectAll(connectionA));
            System.out.println("A : ↑ Non-repeatable reads!");

            System.out.println("A : ** commit **");
            connectionA.commit();

        } catch (SQLException | InterruptedException e) {
            System.out.println(e);
        }
    });

    TimeUnit.SECONDS.sleep(1);

    executor.submit(() -> {
        try (final var connectionB = DriverManager.getConnection(url)) {

            connectionB.setTransactionIsolation(
                    Connection.TRANSACTION_READ_COMMITTED);
            connectionB.setAutoCommit(false);

            System.out.println("B : update : " + product2);
            table.update(connectionB, product2);

            System.out.println("B : ** commit **");
            connectionB.commit();

        } catch (SQLException e) {
            System.out.println(e);
        }
    });
}

// Result
// ↓
//A : select all : [Orange(10)]
//A : sleep ... (5 sec.)
//B : update : Orange(9999)
//B : ** commit **
//A : select all : [Orange(9999)]
//A : ↑ Non-repeatable reads!
//A : ** commit **

static final int TRANSACTION_READ_UNCOMMITTED

A constant indicating that dirty reads, non-repeatable reads and phantom reads can occur.

System.out.println(Connection.TRANSACTION_READ_UNCOMMITTED); // 1
// An example for occurring dirty reads.
final var url = "jdbc:derby:memory:db;create=true";
final var table = new ProductTable();

final var product1 = new Product("Orange", 10);
final var product2 = new Product("Orange", 9999);

// Prepares a table.
try (final var connection = DriverManager.getConnection(url)) {
    table.create(connection);
    table.insert(connection, product1);
}

try (final var executor = Executors.newFixedThreadPool(2)) {

    executor.submit(() -> {
        try (final var connectionA = DriverManager.getConnection(url)) {

            connectionA.setTransactionIsolation(
                    Connection.TRANSACTION_READ_UNCOMMITTED);
            connectionA.setAutoCommit(false);

            System.out.println("A : select all = " + table.selectAll(connectionA));

            System.out.println("A : update : " + product2);
            table.update(connectionA, product2);

            System.out.println("A : sleep ... (3 sec.)");
            TimeUnit.SECONDS.sleep(3);

            System.out.println("A : ** rollback **");
            connectionA.rollback();

        } catch (SQLException | InterruptedException e) {
            System.out.println(e);
        }
    });

    TimeUnit.SECONDS.sleep(1);

    executor.submit(() -> {
        try (final var connectionB = DriverManager.getConnection(url)) {

            connectionB.setTransactionIsolation(
                    Connection.TRANSACTION_READ_UNCOMMITTED);
            connectionB.setAutoCommit(false);

            System.out.println("B : select all = " + table.selectAll(connectionB));
            System.out.println("B : ↑ Dirty reads!");

            System.out.println("B : sleep ... (3 sec.)");
            TimeUnit.SECONDS.sleep(3);

            System.out.println("B : select all = " + table.selectAll(connectionB));

            System.out.println("B : ** commit **");
            connectionB.commit();

        } catch (SQLException | InterruptedException e) {
            System.out.println(e);
        }
    });
}

// Result
// ↓
//A : select all = [Orange(10)]
//A : update : Orange(9999)
//A : sleep ... (3 sec.)
//B : select all = [Orange(9999)]
//B : ↑ Dirty reads!
//B : sleep ... (3 sec.)
//A : ** rollback **
//B : select all = [Orange(10)]
//B : ** commit **

static final int TRANSACTION_REPEATABLE_READ

A constant indicating that dirty reads and non-repeatable reads are prevented; phantom reads can occur.

System.out.println(Connection.TRANSACTION_REPEATABLE_READ); // 4
// An example for occurring phantom reads.
final var url = "jdbc:derby:memory:db;create=true";
final var table = new ProductTable();

final var product1 = new Product("Orange", 10);
final var product2 = new Product("Banana", 20);
final var product3 = new Product("Apple", 30);

// Prepares a table.
try (final var connection = DriverManager.getConnection(url)) {
    table.create(connection);
    table.insert(connection, List.of(product1, product2));
}

try (final var executor = Executors.newFixedThreadPool(2)) {
    executor.submit(() -> {
        try (final var connectionA = DriverManager.getConnection(url)) {

            connectionA.setTransactionIsolation(
                    Connection.TRANSACTION_REPEATABLE_READ);
            connectionA.setAutoCommit(false);

            System.out.println("A : select : " + table.selectAll(connectionA));

            System.out.println("A : sleep ... (5 sec.)");
            TimeUnit.SECONDS.sleep(5);

            System.out.println("A : select : " + table.selectAll(connectionA));
            System.out.println("A : ↑ Phantom reads!");

            System.out.println("A : ** commit **");
            connectionA.commit();

        } catch (SQLException | InterruptedException e) {
            System.out.println(e);
        }
    });

    TimeUnit.SECONDS.sleep(1);

    executor.submit(() -> {
        try (final var connectionB = DriverManager.getConnection(url)) {

            connectionB.setTransactionIsolation(
                    Connection.TRANSACTION_REPEATABLE_READ);
            connectionB.setAutoCommit(false);

            System.out.println("B : insert : " + product3);
            table.insert(connectionB, product3);

            System.out.println("B : ** commit **");
            connectionB.commit();

        } catch (SQLException e) {
            System.out.println(e);
        }
    });
}

// Result
// ↓
//A : select : [Orange(10), Banana(20)]
//A : sleep ... (5 sec.)
//B : insert : Apple(30)
//B : ** commit **
//A : select : [Orange(10), Banana(20), Apple(30)]
//A : ↑ Phantom reads!
//A : ** commit **

static final int TRANSACTION_SERIALIZABLE

A constant indicating that dirty reads, non-repeatable reads and phantom reads are prevented.

System.out.println(Connection.TRANSACTION_SERIALIZABLE); // 8
// An example for preventing phantom leads.
final var url = "jdbc:derby:memory:db;create=true";
final var table = new ProductTable();

final var product1 = new Product("Orange", 10);
final var product2 = new Product("Banana", 20);
final var product3 = new Product("Apple", 30);

// Prepares a table.
try (final var connection = DriverManager.getConnection(url)) {
    table.create(connection);
    table.insert(connection, List.of(product1, product2));
}

try (final var executor = Executors.newFixedThreadPool(2)) {
    executor.submit(() -> {
        try (final var connectionA = DriverManager.getConnection(url)) {

            connectionA.setTransactionIsolation(
                    Connection.TRANSACTION_SERIALIZABLE);
            connectionA.setAutoCommit(false);

            System.out.println("A : select : " + table.selectAll(connectionA));

            System.out.println("A : sleep ... (5 sec.)");
            TimeUnit.SECONDS.sleep(5);

            System.out.println("A : select : " + table.selectAll(connectionA));

            System.out.println("A : ** commit **");
            connectionA.commit();

            System.out.println("A : select : " + table.selectAll(connectionA));

            System.out.println("A : ** commit **");
            connectionA.commit();

        } catch (SQLException | InterruptedException e) {
            System.out.println(e);
        }
    });

    TimeUnit.SECONDS.sleep(1);

    executor.submit(() -> {
        try (final var connectionB = DriverManager.getConnection(url)) {

            connectionB.setTransactionIsolation(
                    Connection.TRANSACTION_SERIALIZABLE);
            connectionB.setAutoCommit(false);

            System.out.println("B : insert : " + product3);
            table.insert(connectionB, product3);

            System.out.println("B : ** commit **");
            connectionB.commit();

        } catch (SQLException e) {
            System.out.println(e);
        }
    });
}

// Result
// ↓
//A : select : [Orange(10), Banana(20)]
//A : sleep ... (5 sec.)
//B : insert : Apple(30)
//A : select : [Orange(10), Banana(20)]
//A : ** commit **
//B : ** commit **
//A : select : [Orange(10), Banana(20), Apple(30)]
//A : ** commit **

Methods

void abort (Executor executor)

Terminates an open connection.

try (final var executor = Executors.newSingleThreadExecutor()) {

    final var url = "jdbc:derby:memory:db;create=true";
    final var table = new ProductTable();

    try (final var connection = DriverManager.getConnection(url)) {
        connection.setAutoCommit(false);

        table.create(connection);
        table.insert(connection, new Product("Orange", 10));
        connection.commit();
        System.out.println(table.selectAll(connection)); // [Orange(10)]

        // No commit.
        table.update(connection, new Product("Orange", 9999));
        System.out.println(table.selectAll(connection)); // [Orange(9999)]

        System.out.println(connection.isClosed()); // false

        connection.abort(executor);
        System.out.println(connection.isClosed()); // true
    }

    try (final var connection = DriverManager.getConnection(url)) {
        System.out.println(table.selectAll(connection)); // [Orange(10)]
    }
}

default void beginRequest ()

Hints to the driver that a request, an independent unit of work, is beginning on this connection.

This method is to be used by Connection pooling managers. I think it's rare to use this method. Therefore, the code example is omitted.

void clearWarnings ()

Clears all warnings reported for this Connection object.

final var url = "jdbc:derby:memory:db;create=true";
try (final var connection = DriverManager.getConnection(url)) {
    // null
    System.out.println(connection.getWarnings());
}

try (final var connection = DriverManager.getConnection(url)) {
    // java.sql.SQLWarning: Database 'memory:db' not created,
    //   connection made to existing database instead.
    System.out.println(connection.getWarnings());

    connection.clearWarnings();

    // null
    System.out.println(connection.getWarnings());
}

void close ()

Releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released.

final var url = "jdbc:derby:memory:db;create=true";
try (final var connection = DriverManager.getConnection(url)) {
    System.out.println(connection.isClosed()); // false
}
// An example without a try-with-resources statement.
final var url = "jdbc:derby:memory:db;create=true";

final var connection = DriverManager.getConnection(url);
try {
    System.out.println(connection.isClosed()); // false
} finally {
    connection.close();
}

System.out.println(connection.isClosed()); // true

void commit ()

Makes all changes made since the previous commit/rollback permanent and releases any database locks currently held by this Connection object.

final var url = "jdbc:derby:memory:db;create=true";
final var table = new ProductTable();

try (final var connection = DriverManager.getConnection(url)) {
    connection.setAutoCommit(false);

    table.create(connection);
    table.insert(connection, new Product("Orange", 10));
    connection.commit();
    System.out.println(table.selectAll(connection)); // [Orange(10)]

    // No commit.
    table.update(connection, new Product("Orange", 9999));
    System.out.println(table.selectAll(connection)); // [Orange(9999)]

    connection.rollback();

    System.out.println(table.selectAll(connection)); // [Orange(10)]

    connection.commit();
}

Array createArrayOf (String typeName, Object[] elements)

Factory method for creating Array objects.

Derby does not support this method.

final var url = "jdbc:derby:memory:db;create=true";
try (final var connection = DriverManager.getConnection(url)) {
    final var ret = connection.createArrayOf("xxx", new String[]{"a", "b", "c"});
} catch (SQLException e) {
    System.out.println(e);
}

// Result
// ↓
//java.sql.SQLFeatureNotSupportedException: Feature not implemented: No details.

Blob createBlob ()

Constructs an object that implements the Blob interface.

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

    try (final var statement = connection.createStatement()) {
        statement.executeUpdate("""
                CREATE TABLE TESTS (
                    VALUE BLOB(1K)
                )
                """);
    }

    try (final var statement = connection.prepareStatement("""
            INSERT INTO TESTS VALUES( ? )
            """)) {

        final var blob = connection.createBlob();
        blob.setBytes(1, new byte[]{10, 20, 30});

        statement.setBlob(1, blob);
        statement.executeUpdate();
    }

    try (final var statement = connection.createStatement()) {
        try (final var result = statement.executeQuery("""
                SELECT * FROM TESTS
                """)) {
            while (result.next()) {
                final var blob = result.getBlob(1);
                final var bytes = blob.getBytes(1, Math.toIntExact(blob.length()));
                System.out.println("value = " + Arrays.toString(bytes));
            }
        }
    }

    // Result
    // ↓
    //value = [10, 20, 30]
}

Clob createClob ()

Constructs an object that implements the Clob interface.

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

    try (final var statement = connection.createStatement()) {
        statement.executeUpdate("""
                CREATE TABLE TESTS (
                    VALUE CLOB(1K)
                )
                """);
    }

    try (final var statement = connection.prepareStatement("""
            INSERT INTO TESTS VALUES( ? )
            """)) {

        final var clob = connection.createClob();
        clob.setString(1, "XYZ");

        statement.setClob(1, clob);
        statement.executeUpdate();
    }

    try (final var statement = connection.createStatement()) {
        try (final var result = statement.executeQuery("""
                SELECT * FROM TESTS
                """)) {
            while (result.next()) {
                final var clob = result.getClob(1);
                final var str = clob.getSubString(1, Math.toIntExact(clob.length()));
                System.out.println("value = " + str);
            }
        }
    }

    // Result
    // ↓
    //value = XYZ
}

NClob createNClob ()

Constructs an object that implements the NClob interface.

Derby does not support this method.

final var url = "jdbc:derby:memory:db;create=true";
try (final var connection = DriverManager.getConnection(url)) {
    final var ret = connection.createNClob();
} catch (SQLException e) {
    System.out.println(e);
}

// Result
// ↓
//java.sql.SQLFeatureNotSupportedException: Feature not implemented: No details.

SQLXML createSQLXML ()

Constructs an object that implements the SQLXML interface.

Derby does not support this method.

final var url = "jdbc:derby:memory:db;create=true";
try (final var connection = DriverManager.getConnection(url)) {
    final var ret = connection.createSQLXML();
} catch (SQLException e) {
    System.out.println(e);
}

// Result
// ↓
//java.sql.SQLFeatureNotSupportedException: Feature not implemented: No details.

Statement createStatement ()

Creates a Statement object for sending SQL statements to the database.

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
}

Statement createStatement (int resultSetType, int resultSetConcurrency)

Creates a Statement object that will generate ResultSet objects with the given type and concurrency.

final var url = "jdbc:derby:memory:db;create=true";
final var table = new ProductTable();

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

try (final var connection = DriverManager.getConnection(url)) {

    table.create(connection);
    table.insert(connection, products);

    System.out.println("-- select --");
    try (final var statement = connection.createStatement(
            ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) {

        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.updateInt("STOCK", stock / 2);
                result.updateRow();
            }
        }
    }

    // Result
    // ↓
    //-- select --
    //Orange : 10
    //Banana : 20
    //Apple : 30

    System.out.println("-- select --");
    try (final var statement = connection.createStatement(
            ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) {

        try (final var result = statement.executeQuery("""
                SELECT * FROM PRODUCTS
                """)) {

            result.afterLast();
            while (result.previous()) {
                final var name = result.getString("NAME");
                final var stock = result.getInt("STOCK");

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

    // Result
    // ↓
    //-- select --
    //Apple : 15
    //Banana : 10
    //Orange : 5
}

Statement createStatement (int resultSetType, int resultSetConcurrency, int resultSetHoldability)

Creates a Statement object that will generate ResultSet objects with the given type, concurrency, and holdability.

Please see also : createStatement(int resultSetType, int resultSetConcurrency)

final var url = "jdbc:derby:memory:db;create=true";
final var table = new ProductTable();

try (final var connection = DriverManager.getConnection(url)) {

    table.create(connection);
    table.insert(connection, new Product("Orange", 10));

    connection.setAutoCommit(false);

    try (final var statement = connection.createStatement(
            ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY,
            ResultSet.CLOSE_CURSORS_AT_COMMIT)) {

        try (final var result = statement.executeQuery("""
                SELECT * FROM PRODUCTS
                """)) {

            System.out.println(result.isClosed()); // false

            connection.commit();
            System.out.println(result.isClosed()); // true
        }
    }
}

Struct createStruct (String typeName, Object[] attributes)

Factory method for creating Struct objects.

Derby does not support this method.

final var url = "jdbc:derby:memory:db;create=true";
try (final var connection = DriverManager.getConnection(url)) {
    final var ret = connection.createStruct("xxx", new String[]{"a", "b", "c"});
} catch (SQLException e) {
    System.out.println(e);
}

// Result
// ↓
//java.sql.SQLFeatureNotSupportedException: Feature not implemented: No details.

default void endRequest ()

Hints to the driver that a request, an independent unit of work, has completed.

This method is to be used by Connection pooling managers. I think it's rare to use this method. Therefore, the code example is omitted.

boolean getAutoCommit ()

Retrieves the current auto-commit mode for this Connection object.

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

    final var ret1 = connection.getAutoCommit();
    System.out.println(ret1); // true

    connection.setAutoCommit(false);

    final var ret2 = connection.getAutoCommit();
    System.out.println(ret2); // false
}
final var url = "jdbc:derby:memory:db;create=true";
final var table = new ProductTable();

try (final var connection = DriverManager.getConnection(url)) {
    connection.setAutoCommit(false);

    table.create(connection);
    table.insert(connection, new Product("Orange", 10));
    connection.commit();
    System.out.println(table.selectAll(connection)); // [Orange(10)]

    // No commit.
    table.update(connection, new Product("Orange", 9999));
    System.out.println(table.selectAll(connection)); // [Orange(9999)]

    connection.rollback();

    System.out.println(table.selectAll(connection)); // [Orange(10)]

    connection.commit();
}

String getCatalog ()

Retrieves this Connection object's current catalog name.

Derby does not support this method.

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

    final var meta = connection.getMetaData();
    System.out.println(meta.supportsCatalogsInDataManipulation()); // false

    System.out.println(connection.getCatalog()); // null

    connection.setCatalog("XYZ");
    System.out.println(connection.getCatalog()); // null
}

Properties getClientInfo ()

Returns a list containing the name and current value of each client info property supported by the driver.

Derby does not support this method.

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

    System.out.println(connection.getClientInfo()); // {}
    System.out.println(connection.getClientInfo("aaa")); // null

    try {
        connection.setClientInfo("aaa", "XXX");
    } catch (SQLClientInfoException e) {
        System.out.println(e);
    }

    // Result
    // ↓
    //java.sql.SQLClientInfoException:
    //  The requested property change is not supported 'aaa'='XXX'.

    try {
        final var properties = new Properties();
        properties.setProperty("aaa", "XXX");
        connection.setClientInfo(properties);
    } catch (SQLClientInfoException e) {
        System.out.println(e);
    }

    // Result
    // ↓
    //java.sql.SQLClientInfoException:
    //  The requested property change is not supported 'aaa'='XXX'.
}

String getClientInfo (String name)

Returns the value of the client info property specified by name.

Derby does not support this method.

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

    System.out.println(connection.getClientInfo()); // {}
    System.out.println(connection.getClientInfo("aaa")); // null

    try {
        connection.setClientInfo("aaa", "XXX");
    } catch (SQLClientInfoException e) {
        System.out.println(e);
    }

    // Result
    // ↓
    //java.sql.SQLClientInfoException:
    //  The requested property change is not supported 'aaa'='XXX'.

    try {
        final var properties = new Properties();
        properties.setProperty("aaa", "XXX");
        connection.setClientInfo(properties);
    } catch (SQLClientInfoException e) {
        System.out.println(e);
    }

    // Result
    // ↓
    //java.sql.SQLClientInfoException:
    //  The requested property change is not supported 'aaa'='XXX'.
}

int getHoldability ()

Retrieves the current holdability of ResultSet objects created using this Connection object.

final var url = "jdbc:derby:memory:db;create=true";
final var table = new ProductTable();

try (final var connection = DriverManager.getConnection(url)) {

    table.create(connection);
    table.insert(connection, new Product("Orange", 10));

    connection.setAutoCommit(false);

    final var ret1 = connection.getHoldability();
    System.out.println(ret1 == ResultSet.HOLD_CURSORS_OVER_COMMIT); // true

    try (final var statement = connection.createStatement()) {

        try (final var result = statement.executeQuery("""
                SELECT * FROM PRODUCTS
                """)) {

            System.out.println(result.isClosed()); // false

            connection.commit();
            System.out.println(result.isClosed()); // false
        }
    }

    connection.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);

    final var ret2 = connection.getHoldability();
    System.out.println(ret2 == ResultSet.CLOSE_CURSORS_AT_COMMIT); // true

    try (final var statement = connection.createStatement()) {

        try (final var result = statement.executeQuery("""
                SELECT * FROM PRODUCTS
                """)) {

            System.out.println(result.isClosed()); // false

            connection.commit();
            System.out.println(result.isClosed()); // true
        }
    }
}

DatabaseMetaData getMetaData ()

Retrieves a DatabaseMetaData object that contains metadata about the database to which this Connection object represents a connection.

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

    final var meta = connection.getMetaData();
    System.out.println(meta.getDatabaseProductName()); // Apache Derby
    System.out.println(meta.getUserName()); // APP
}

int getNetworkTimeout ()

Retrieves the number of milliseconds the driver will wait for a database request to complete.

Derby does not support this method.

final var url = "jdbc:derby://localhost:1527/db;create=true";
try (final var connection = DriverManager.getConnection(url)) {
    final var ret = connection.getNetworkTimeout();
} catch (SQLFeatureNotSupportedException e) {
    System.out.println("SQLFeatureNotSupportedException!");
}

// Result
// ↓
//SQLFeatureNotSupportedException!

String getSchema ()

Retrieves this Connection object's current schema name.

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

    final var ret1 = connection.getSchema();
    System.out.println(ret1); // APP

    try (final var statement = connection.createStatement()) {
        statement.executeUpdate("""
                CREATE SCHEMA TEST
                """);
    }

    connection.setSchema("TEST");

    final var ret2 = connection.getSchema();
    System.out.println(ret2); // TEST
}

int getTransactionIsolation ()

Retrieves this Connection object's current transaction isolation level.

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

    final var ret1 = connection.getTransactionIsolation();
    System.out.println(ret1 == Connection.TRANSACTION_READ_COMMITTED); // true

    connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);

    final var ret2 = connection.getTransactionIsolation();
    System.out.println(ret2 == Connection.TRANSACTION_SERIALIZABLE); // true
}

Map<String,Class<?>> getTypeMap ()

Retrieves the Map object associated with this Connection object.

Derby does not support this method.

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

    System.out.println(connection.getTypeMap()); // {}

    try {
        connection.setTypeMap(Map.of("dummy", Object.class));
    } catch (SQLFeatureNotSupportedException e) {
        System.out.println(e);
    }

    // Result
    // ↓
    //java.sql.SQLFeatureNotSupportedException: Feature not implemented: No details.
}

SQLWarning getWarnings ()

Retrieves the first warning reported by calls on this Connection object.

final var url = "jdbc:derby:memory:db;create=true";
try (final var connection = DriverManager.getConnection(url)) {
    // null
    System.out.println(connection.getWarnings());
}

try (final var connection = DriverManager.getConnection(url)) {
    // java.sql.SQLWarning: Database 'memory:db' not created,
    //   connection made to existing database instead.
    System.out.println(connection.getWarnings());

    connection.clearWarnings();

    // null
    System.out.println(connection.getWarnings());
}

boolean isClosed ()

Retrieves whether this Connection object has been closed.

final var url = "jdbc:derby:memory:db;create=true";
try (final var connection = DriverManager.getConnection(url)) {
    System.out.println(connection.isClosed()); // false
}
// An example without a try-with-resources statement.
final var url = "jdbc:derby:memory:db;create=true";

final var connection = DriverManager.getConnection(url);
try {
    System.out.println(connection.isClosed()); // false
} finally {
    connection.close();
}

System.out.println(connection.isClosed()); // true

boolean isReadOnly ()

Retrieves whether this Connection object is in read-only mode.

final var url = "jdbc:derby:memory:db;create=true";
final var table = new ProductTable();

try (final var connection = DriverManager.getConnection(url)) {

    System.out.println(connection.isReadOnly()); // false

    table.create(connection);
    table.insert(connection, new Product("Orange", 10));
    System.out.println(table.selectAll(connection)); // [Orange(10)]

    table.update(connection, new Product("Orange", 20));
    System.out.println(table.selectAll(connection)); // [Orange(20)]

    connection.setReadOnly(true);
    System.out.println(connection.isReadOnly()); // true

    try {
        table.update(connection, new Product("Orange", 30));
    } catch (SQLException e) {
        System.out.println(e);
    }

    // Result
    // ↓
    //java.sql.SQLException: An SQL data change is not permitted
    //  for a read-only connection, user or database.
}

boolean isValid (int timeout)

Returns true if the connection has not been closed and is still valid.

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

    System.out.println(connection.isValid(1)); // true

    connection.close();
    System.out.println(connection.isValid(1)); // false
}

String nativeSQL (String sql)

Converts the given SQL statement into the system's native SQL grammar.

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

    final var ret = connection.nativeSQL("SELECT * FROM PRODUCTS");
    System.out.println(ret); // SELECT * FROM PRODUCTS
}

CallableStatement prepareCall (String sql)

Creates a CallableStatement object for calling database stored procedures.

package com.example.sql.connection;

public class Procedure {
    public static void test(int value, int[] result) {
        result[0] = value * 5;
    }
}
final var url = "jdbc:derby:memory:db;create=true";

try (final var connection = DriverManager.getConnection(url)) {
    try (final var statement = connection.createStatement()) {
        statement.executeUpdate("""
                CREATE PROCEDURE TEST(
                    IN VALUE INTEGER,
                    OUT RESULT INTEGER
                )
                LANGUAGE JAVA
                PARAMETER STYLE JAVA
                NO SQL
                EXTERNAL NAME 'com.example.sql.connection.Procedure.test'
                """);
    }

    try (final var statement = connection.prepareCall("""
            CALL TEST( ?, ? )
            """)) {
        statement.setInt(1, 100);
        statement.registerOutParameter(2, Types.INTEGER);
        statement.execute();

        System.out.println(statement.getInt(2)); // 500
    }
}

CallableStatement prepareCall (String sql, int resultSetType, int resultSetConcurrency)

Creates a CallableStatement object that will generate ResultSet objects with the given type and concurrency.

Please see also : createStatement(int resultSetType, int resultSetConcurrency)

package com.example.sql.connection;

public class Procedure {
    public static void test(int value, int[] result) {
        result[0] = value * 5;
    }
}
final var url = "jdbc:derby:memory:db;create=true";

try (final var connection = DriverManager.getConnection(url)) {
    try (final var statement = connection.createStatement()) {
        statement.executeUpdate("""
                CREATE PROCEDURE TEST(
                    IN VALUE INTEGER,
                    OUT RESULT INTEGER
                )
                LANGUAGE JAVA
                PARAMETER STYLE JAVA
                NO SQL
                EXTERNAL NAME 'com.example.sql.connection.Procedure.test'
                """);
    }

    try (final var statement = connection.prepareCall("""
            CALL TEST( ?, ? )
            """, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) {
        statement.setInt(1, 100);
        statement.registerOutParameter(2, Types.INTEGER);
        statement.execute();

        System.out.println(statement.getInt(2)); // 500
    }
}

CallableStatement prepareCall (String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability)

Creates a CallableStatement object that will generate ResultSet objects with the given type and concurrency.

Please see also : createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability)

package com.example.sql.connection;

public class Procedure {
    public static void test(int value, int[] result) {
        result[0] = value * 5;
    }
}
final var url = "jdbc:derby:memory:db;create=true";

try (final var connection = DriverManager.getConnection(url)) {
    try (final var statement = connection.createStatement()) {
        statement.executeUpdate("""
                CREATE PROCEDURE TEST(
                    IN VALUE INTEGER,
                    OUT RESULT INTEGER
                )
                LANGUAGE JAVA
                PARAMETER STYLE JAVA
                NO SQL
                EXTERNAL NAME 'com.example.sql.connection.Procedure.test'
                """);
    }

    try (final var statement = connection.prepareCall("""
                    CALL TEST( ?, ? )
                    """, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY,
            ResultSet.HOLD_CURSORS_OVER_COMMIT)) {
        statement.setInt(1, 100);
        statement.registerOutParameter(2, Types.INTEGER);
        statement.execute();

        System.out.println(statement.getInt(2)); // 500
    }
}

PreparedStatement prepareStatement (String sql)

Creates a PreparedStatement object for sending parameterized SQL statements to the database.

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
}

PreparedStatement prepareStatement (String sql, int autoGeneratedKeys)

Creates a default PreparedStatement object that has the capability to retrieve auto-generated keys.

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()) {
        statement.executeUpdate("""
                CREATE TABLE TESTS (
                    ID INTEGER GENERATED ALWAYS AS IDENTITY,
                    NAME VARCHAR(20)
                )
                """);
    }

    System.out.println("-- insert --");
    try (final var statement = connection.prepareStatement("""
            INSERT INTO TESTS( NAME ) VALUES ( ? )
            """, Statement.RETURN_GENERATED_KEYS)) {
        for (final var name : List.of("a", "b", "c")) {
            statement.setString(1, name);
            statement.executeUpdate();

            try (final var keys = statement.getGeneratedKeys()) {
                while (keys.next()) {
                    final var id = keys.getInt(1);
                    System.out.printf("id = %d, name = %s%n", id, name);
                }
            }
        }
    }

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

                System.out.printf("id = %d, name = %s%n", id, name);
            }
        }
    }

    // Result
    // ↓
    //-- create table --
    //-- insert --
    //id = 1, name = a
    //id = 2, name = b
    //id = 3, name = c
    //-- select --
    //id = 1, name = a
    //id = 2, name = b
    //id = 3, name = c
}

PreparedStatement prepareStatement (String sql, int[] columnIndexes)

Creates a default PreparedStatement object capable of returning the auto-generated keys designated by the given array.

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()) {
        statement.executeUpdate("""
                CREATE TABLE TESTS (
                    ID INTEGER GENERATED ALWAYS AS IDENTITY,
                    NAME VARCHAR(20)
                )
                """);
    }

    System.out.println("-- insert --");
    final int[] columnIndexes = {1};
    try (final var statement = connection.prepareStatement("""
            INSERT INTO TESTS( NAME ) VALUES( ? )
            """, columnIndexes)) {
        for (final var name : List.of("a", "b", "c")) {
            statement.setString(1, name);
            statement.executeUpdate();

            try (final var keys = statement.getGeneratedKeys()) {
                while (keys.next()) {
                    final var id = keys.getInt(1);
                    System.out.printf("id = %d, name = %s%n", id, name);
                }
            }
        }
    }

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

                System.out.printf("id = %d, name = %s%n", id, name);
            }
        }
    }

    // Result
    // ↓
    //-- create table --
    //-- insert --
    //id = 1, name = a
    //id = 2, name = b
    //id = 3, name = c
    //-- select --
    //id = 1, name = a
    //id = 2, name = b
    //id = 3, name = c
}

PreparedStatement prepareStatement (String sql, int resultSetType, int resultSetConcurrency)

Creates a PreparedStatement object that will generate ResultSet objects with the given type and concurrency.

final var url = "jdbc:derby:memory:db;create=true";
final var table = new ProductTable();

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

try (final var connection = DriverManager.getConnection(url)) {

    table.create(connection);
    table.insert(connection, products);

    System.out.println("-- select --");
    try (final var statement = connection.prepareStatement("""
            SELECT * FROM PRODUCTS
            """, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) {

        try (final var result = statement.executeQuery()) {
            while (result.next()) {
                final var name = result.getString("NAME");
                final var stock = result.getInt("STOCK");

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

                result.updateInt("STOCK", stock / 2);
                result.updateRow();
            }
        }
    }

    // Result
    // ↓
    //-- select --
    //Orange : 10
    //Banana : 20
    //Apple : 30

    System.out.println("-- select --");
    try (final var statement = connection.prepareStatement("""
            SELECT * FROM PRODUCTS
            """, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) {

        try (final var result = statement.executeQuery()) {

            result.afterLast();
            while (result.previous()) {
                final var name = result.getString("NAME");
                final var stock = result.getInt("STOCK");

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

    // Result
    // ↓
    //-- select --
    //Apple : 15
    //Banana : 10
    //Orange : 5
}

PreparedStatement prepareStatement (String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability)

Creates a PreparedStatement object that will generate ResultSet objects with the given type, concurrency, and holdability.

Please see also : prepareStatement(String sql, int resultSetType, int resultSetConcurrency)

final var url = "jdbc:derby:memory:db;create=true";
final var table = new ProductTable();

try (final var connection = DriverManager.getConnection(url)) {

    table.create(connection);
    table.insert(connection, new Product("Orange", 10));

    connection.setAutoCommit(false);

    try (final var statement = connection.prepareStatement("""
                    SELECT * FROM PRODUCTS
                    """,
            ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY,
            ResultSet.CLOSE_CURSORS_AT_COMMIT)) {

        try (final var result = statement.executeQuery()) {

            System.out.println(result.isClosed()); // false

            connection.commit();
            System.out.println(result.isClosed()); // true
        }
    }
}

PreparedStatement prepareStatement (String sql, String[] columnNames)

Creates a default PreparedStatement object capable of returning the auto-generated keys designated by the given array.

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()) {
        statement.executeUpdate("""
                CREATE TABLE TESTS (
                    ID INTEGER GENERATED ALWAYS AS IDENTITY,
                    NAME VARCHAR(20)
                )
                """);
    }

    System.out.println("-- insert --");
    final String[] columnNames = {"ID"};
    try (final var statement = connection.prepareStatement("""
            INSERT INTO TESTS( NAME ) VALUES( ? )
            """, columnNames)) {
        for (final var name : List.of("a", "b", "c")) {
            statement.setString(1, name);
            statement.executeUpdate();

            try (final var keys = statement.getGeneratedKeys()) {
                while (keys.next()) {
                    final var id = keys.getInt(1);
                    System.out.printf("id = %d, name = %s%n", id, name);
                }
            }
        }
    }

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

                System.out.printf("id = %d, name = %s%n", id, name);
            }
        }
    }

    // Result
    // ↓
    //-- create table --
    //-- insert --
    //id = 1, name = a
    //id = 2, name = b
    //id = 3, name = c
    //-- select --
    //id = 1, name = a
    //id = 2, name = b
    //id = 3, name = c
}

void releaseSavepoint (Savepoint savepoint)

Removes the specified Savepoint and subsequent Savepoint objects from the current transaction.

final var url = "jdbc:derby:memory:db;create=true";
final var table = new ProductTable();

try (final var connection = DriverManager.getConnection(url)) {
    connection.setAutoCommit(false);

    table.create(connection);
    table.insert(connection, new Product("Orange", 10));

    connection.commit();
    System.out.println(table.selectAll(connection)); // [Orange(10)]

    // No commit.
    table.update(connection, new Product("Orange", 20));
    System.out.println(table.selectAll(connection)); // [Orange(20)]

    final var savepoint = connection.setSavepoint();
    System.out.println(savepoint.getSavepointId()); // 1

    table.update(connection, new Product("Orange", 30));
    System.out.println(table.selectAll(connection)); // [Orange(30)]

    connection.releaseSavepoint(savepoint);

    try {
        connection.rollback(savepoint);
    } catch (SQLException e) {
        System.out.println(e);
        connection.rollback();
    }

    // Result
    // ↓
    //java.sql.SQLException: SAVEPOINT,
    //  SAVEPT1 does not  exist or is not active in the current transaction.
}

void rollback ()

Undoes all changes made in the current transaction and releases any database locks currently held by this Connection object.

final var url = "jdbc:derby:memory:db;create=true";
final var table = new ProductTable();

try (final var connection = DriverManager.getConnection(url)) {
    connection.setAutoCommit(false);

    table.create(connection);
    table.insert(connection, new Product("Orange", 10));
    connection.commit();
    System.out.println(table.selectAll(connection)); // [Orange(10)]

    // No commit.
    table.update(connection, new Product("Orange", 9999));
    System.out.println(table.selectAll(connection)); // [Orange(9999)]

    connection.rollback();

    System.out.println(table.selectAll(connection)); // [Orange(10)]

    connection.commit();
}

void rollback (Savepoint savepoint)

Undoes all changes made after the given Savepoint object was set.

final var url = "jdbc:derby:memory:db;create=true";
final var table = new ProductTable();

try (final var connection = DriverManager.getConnection(url)) {
    connection.setAutoCommit(false);

    table.create(connection);
    table.insert(connection, new Product("Orange", 10));

    connection.commit();
    System.out.println(table.selectAll(connection)); // [Orange(10)]

    // No commit.
    table.update(connection, new Product("Orange", 20));
    System.out.println(table.selectAll(connection)); // [Orange(20)]

    final var savepoint1 = connection.setSavepoint();
    System.out.println(savepoint1.getSavepointId()); // 1

    table.update(connection, new Product("Orange", 30));
    System.out.println(table.selectAll(connection)); // [Orange(30)]

    final var savepoint2 = connection.setSavepoint("XYZ");
    System.out.println(savepoint2.getSavepointName()); // XYZ

    table.update(connection, new Product("Orange", 40));
    System.out.println(table.selectAll(connection)); // [Orange(40)]

    connection.rollback(savepoint2);
    System.out.println(table.selectAll(connection)); // [Orange(30)]

    connection.rollback(savepoint1);
    System.out.println(table.selectAll(connection)); // [Orange(20)]

    connection.commit();
}

void setAutoCommit (boolean autoCommit)

Sets this connection's auto-commit mode to the given state.

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

    final var ret1 = connection.getAutoCommit();
    System.out.println(ret1); // true

    connection.setAutoCommit(false);

    final var ret2 = connection.getAutoCommit();
    System.out.println(ret2); // false
}
final var url = "jdbc:derby:memory:db;create=true";
final var table = new ProductTable();

try (final var connection = DriverManager.getConnection(url)) {
    connection.setAutoCommit(false);

    table.create(connection);
    table.insert(connection, new Product("Orange", 10));
    connection.commit();
    System.out.println(table.selectAll(connection)); // [Orange(10)]

    // No commit.
    table.update(connection, new Product("Orange", 9999));
    System.out.println(table.selectAll(connection)); // [Orange(9999)]

    connection.rollback();

    System.out.println(table.selectAll(connection)); // [Orange(10)]

    connection.commit();
}

void setCatalog (String catalog)

Sets the given catalog name in order to select a subspace of this Connection object's database in which to work.

Derby does not support this method.

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

    final var meta = connection.getMetaData();
    System.out.println(meta.supportsCatalogsInDataManipulation()); // false

    System.out.println(connection.getCatalog()); // null

    connection.setCatalog("XYZ");
    System.out.println(connection.getCatalog()); // null
}

void setClientInfo (String name, String value)

Sets the value of the client info property specified by name to the value specified by value.

Derby does not support this method.

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

    System.out.println(connection.getClientInfo()); // {}
    System.out.println(connection.getClientInfo("aaa")); // null

    try {
        connection.setClientInfo("aaa", "XXX");
    } catch (SQLClientInfoException e) {
        System.out.println(e);
    }

    // Result
    // ↓
    //java.sql.SQLClientInfoException:
    //  The requested property change is not supported 'aaa'='XXX'.

    try {
        final var properties = new Properties();
        properties.setProperty("aaa", "XXX");
        connection.setClientInfo(properties);
    } catch (SQLClientInfoException e) {
        System.out.println(e);
    }

    // Result
    // ↓
    //java.sql.SQLClientInfoException:
    //  The requested property change is not supported 'aaa'='XXX'.
}

void setClientInfo (Properties properties)

Sets the value of the connection's client info properties.

Derby does not support this method.

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

    System.out.println(connection.getClientInfo()); // {}
    System.out.println(connection.getClientInfo("aaa")); // null

    try {
        connection.setClientInfo("aaa", "XXX");
    } catch (SQLClientInfoException e) {
        System.out.println(e);
    }

    // Result
    // ↓
    //java.sql.SQLClientInfoException:
    //  The requested property change is not supported 'aaa'='XXX'.

    try {
        final var properties = new Properties();
        properties.setProperty("aaa", "XXX");
        connection.setClientInfo(properties);
    } catch (SQLClientInfoException e) {
        System.out.println(e);
    }

    // Result
    // ↓
    //java.sql.SQLClientInfoException:
    //  The requested property change is not supported 'aaa'='XXX'.
}

void setHoldability (int holdability)

Changes the default holdability of ResultSet objects created using this Connection object to the given holdability.

final var url = "jdbc:derby:memory:db;create=true";
final var table = new ProductTable();

try (final var connection = DriverManager.getConnection(url)) {

    table.create(connection);
    table.insert(connection, new Product("Orange", 10));

    connection.setAutoCommit(false);

    final var ret1 = connection.getHoldability();
    System.out.println(ret1 == ResultSet.HOLD_CURSORS_OVER_COMMIT); // true

    try (final var statement = connection.createStatement()) {

        try (final var result = statement.executeQuery("""
                SELECT * FROM PRODUCTS
                """)) {

            System.out.println(result.isClosed()); // false

            connection.commit();
            System.out.println(result.isClosed()); // false
        }
    }

    connection.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);

    final var ret2 = connection.getHoldability();
    System.out.println(ret2 == ResultSet.CLOSE_CURSORS_AT_COMMIT); // true

    try (final var statement = connection.createStatement()) {

        try (final var result = statement.executeQuery("""
                SELECT * FROM PRODUCTS
                """)) {

            System.out.println(result.isClosed()); // false

            connection.commit();
            System.out.println(result.isClosed()); // true
        }
    }
}

void setNetworkTimeout (Executor executor, int milliseconds)

Sets the maximum period a Connection or objects created from the Connection will wait for the database to reply to any one request.

Derby does not support this method.

try (final var executor = Executors.newSingleThreadExecutor()) {

    final var url = "jdbc:derby://localhost:1527/db;create=true";
    try (final var connection = DriverManager.getConnection(url)) {
        connection.setNetworkTimeout(executor, 120);
    } catch (SQLFeatureNotSupportedException e) {
        System.out.println("SQLFeatureNotSupportedException!");
    }

    // Result
    // ↓
    //SQLFeatureNotSupportedException!
}

void setReadOnly (boolean readOnly)

Puts this connection in read-only mode as a hint to the driver to enable database optimizations.

final var url = "jdbc:derby:memory:db;create=true";
final var table = new ProductTable();

try (final var connection = DriverManager.getConnection(url)) {

    System.out.println(connection.isReadOnly()); // false

    table.create(connection);
    table.insert(connection, new Product("Orange", 10));
    System.out.println(table.selectAll(connection)); // [Orange(10)]

    table.update(connection, new Product("Orange", 20));
    System.out.println(table.selectAll(connection)); // [Orange(20)]

    connection.setReadOnly(true);
    System.out.println(connection.isReadOnly()); // true

    try {
        table.update(connection, new Product("Orange", 30));
    } catch (SQLException e) {
        System.out.println(e);
    }

    // Result
    // ↓
    //java.sql.SQLException: An SQL data change is not permitted
    //  for a read-only connection, user or database.
}

Savepoint setSavepoint ()

Creates an unnamed savepoint in the current transaction and returns the new Savepoint object that represents it.

final var url = "jdbc:derby:memory:db;create=true";
final var table = new ProductTable();

try (final var connection = DriverManager.getConnection(url)) {
    connection.setAutoCommit(false);

    table.create(connection);
    table.insert(connection, new Product("Orange", 10));

    connection.commit();
    System.out.println(table.selectAll(connection)); // [Orange(10)]

    // No commit.
    table.update(connection, new Product("Orange", 20));
    System.out.println(table.selectAll(connection)); // [Orange(20)]

    final var savepoint1 = connection.setSavepoint();
    System.out.println(savepoint1.getSavepointId()); // 1

    table.update(connection, new Product("Orange", 30));
    System.out.println(table.selectAll(connection)); // [Orange(30)]

    final var savepoint2 = connection.setSavepoint("XYZ");
    System.out.println(savepoint2.getSavepointName()); // XYZ

    table.update(connection, new Product("Orange", 40));
    System.out.println(table.selectAll(connection)); // [Orange(40)]

    connection.rollback(savepoint2);
    System.out.println(table.selectAll(connection)); // [Orange(30)]

    connection.rollback(savepoint1);
    System.out.println(table.selectAll(connection)); // [Orange(20)]

    connection.commit();
}

Savepoint setSavepoint (String name)

Creates a savepoint with the given name in the current transaction and returns the new Savepoint object that represents it.

final var url = "jdbc:derby:memory:db;create=true";
final var table = new ProductTable();

try (final var connection = DriverManager.getConnection(url)) {
    connection.setAutoCommit(false);

    table.create(connection);
    table.insert(connection, new Product("Orange", 10));

    connection.commit();
    System.out.println(table.selectAll(connection)); // [Orange(10)]

    // No commit.
    table.update(connection, new Product("Orange", 20));
    System.out.println(table.selectAll(connection)); // [Orange(20)]

    final var savepoint1 = connection.setSavepoint();
    System.out.println(savepoint1.getSavepointId()); // 1

    table.update(connection, new Product("Orange", 30));
    System.out.println(table.selectAll(connection)); // [Orange(30)]

    final var savepoint2 = connection.setSavepoint("XYZ");
    System.out.println(savepoint2.getSavepointName()); // XYZ

    table.update(connection, new Product("Orange", 40));
    System.out.println(table.selectAll(connection)); // [Orange(40)]

    connection.rollback(savepoint2);
    System.out.println(table.selectAll(connection)); // [Orange(30)]

    connection.rollback(savepoint1);
    System.out.println(table.selectAll(connection)); // [Orange(20)]

    connection.commit();
}

void setSchema (String schema)

Sets the given schema name to access.

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

    final var ret1 = connection.getSchema();
    System.out.println(ret1); // APP

    try (final var statement = connection.createStatement()) {
        statement.executeUpdate("""
                CREATE SCHEMA TEST
                """);
    }

    connection.setSchema("TEST");

    final var ret2 = connection.getSchema();
    System.out.println(ret2); // TEST
}

default void setShardingKey (ShardingKey shardingKey)

Specifies a shardingKey to use with this Connection

Derby does not support this method.

final var url = "jdbc:derby:memory:db;create=true";
try (final var connection = DriverManager.getConnection(url)) {
    connection.setShardingKey(null);
} catch (SQLFeatureNotSupportedException e) {
    System.out.println(e);
}

// Result
// ↓
//java.sql.SQLFeatureNotSupportedException: setShardingKey not implemented

default void setShardingKey (ShardingKey shardingKey, ShardingKey superShardingKey)

Specifies a shardingKey and superShardingKey to use with this Connection

Derby does not support this method.

final var url = "jdbc:derby:memory:db;create=true";
try (final var connection = DriverManager.getConnection(url)) {
    connection.setShardingKey(null, null);
} catch (SQLFeatureNotSupportedException e) {
    System.out.println(e);
}

// Result
// ↓
//java.sql.SQLFeatureNotSupportedException: setShardingKey not implemented

default boolean setShardingKeyIfValid (ShardingKey shardingKey, int timeout)

Sets and validates the sharding key for this connection.

Derby does not support this method.

final var url = "jdbc:derby:memory:db;create=true";
try (final var connection = DriverManager.getConnection(url)) {
    connection.setShardingKeyIfValid(null, 0);
} catch (SQLFeatureNotSupportedException e) {
    System.out.println(e);
}

// Result
// ↓
//java.sql.SQLFeatureNotSupportedException: setShardingKeyIfValid not implemented

default boolean setShardingKeyIfValid (ShardingKey shardingKey, ShardingKey superShardingKey, int timeout)

Sets and validates the sharding keys for this connection.

Derby does not support this method.

final var url = "jdbc:derby:memory:db;create=true";
try (final var connection = DriverManager.getConnection(url)) {
    connection.setShardingKeyIfValid(null, null, 0);
} catch (SQLFeatureNotSupportedException e) {
    System.out.println(e);
}

// Result
// ↓
//java.sql.SQLFeatureNotSupportedException: setShardingKeyIfValid not implemented

void setTransactionIsolation (int level)

Attempts to change the transaction isolation level for this Connection object to the one given.

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

    final var ret1 = connection.getTransactionIsolation();
    System.out.println(ret1 == Connection.TRANSACTION_READ_COMMITTED); // true

    connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);

    final var ret2 = connection.getTransactionIsolation();
    System.out.println(ret2 == Connection.TRANSACTION_SERIALIZABLE); // true
}

void setTypeMap (Map<String,Class<?>> map)

Installs the given TypeMap object as the type map for this Connection object.

Derby does not support this method.

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

    System.out.println(connection.getTypeMap()); // {}

    try {
        connection.setTypeMap(Map.of("dummy", Object.class));
    } catch (SQLFeatureNotSupportedException e) {
        System.out.println(e);
    }

    // Result
    // ↓
    //java.sql.SQLFeatureNotSupportedException: Feature not implemented: No details.
}

Methods declared in Wrapper

isWrapperFor, unwrap

Please see the link below.


Related posts

To top of page