Java : Connection (JDBC) con ejemplos

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

Nota :


Summary

Una conexión (sesión) con una base de datos específica. Las instrucciones SQL se ejecutan y los resultados se devuelven dentro del contexto de una conexión. (Traducción automática)

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

Una constante que indica que no se admiten transacciones. (Traducción automática)

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

Una constante que indica que se evitan las lecturas sucias; pueden ocurrir lecturas no repetibles y lecturas fantasmas. (Traducción automática)

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

Una constante que indica que pueden ocurrir lecturas sucias, lecturas no repetibles y lecturas fantasmas. (Traducción automática)

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

Una constante que indica que se evitan las lecturas sucias y no repetibles; pueden producirse lecturas fantasmas. (Traducción automática)

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

Una constante que indica que se evitan las lecturas sucias, las lecturas no repetibles y las lecturas fantasmas. (Traducción automática)

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)

Termina una conexión abierta. (Traducción automática)

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

Indica al conductor que en esta conexión se inicia una solicitud, una unidad de trabajo independiente. (Traducción automática)

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

Borra todas las advertencias informadas para este objeto de conexión. (Traducción automática)

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

Libera la base de datos y los recursos JDBC de este objeto de conexión inmediatamente en lugar de esperar a que se liberen automáticamente. (Traducción automática)

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

Hace que todos los cambios realizados desde la confirmación/reversión anterior sean permanentes y libera cualquier bloqueo de base de datos que este objeto Connection tenga actualmente. (Traducción automática)

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)

Método de fábrica para crear objetos Array. (Traducción automática)

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

Construye un objeto que implementa la interfaz Blob. (Traducción automática)

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

Construye un objeto que implementa la interfaz Clob. (Traducción automática)

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

Construye un objeto que implementa la interfaz NClob. (Traducción automática)

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

Construye un objeto que implementa la interfaz SQLXML. (Traducción automática)

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

Crea un objeto de declaración para enviar declaraciones SQL a la base de datos. (Traducción automática)

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)

Crea un objeto Statement que generará objetos ResultSet con el tipo y simultaneidad indicados. (Traducción automática)

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)

Crea un objeto Statement que generará objetos ResultSet con el tipo, la simultaneidad y la capacidad de retención indicados. (Traducción automática)

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)

Método de fábrica para crear objetos Struct. (Traducción automática)

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

Indica al conductor que se ha completado una solicitud, una unidad de trabajo independiente. (Traducción automática)

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

Recupera el modo de confirmación automática actual para este objeto de conexión. (Traducción automática)

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

Recupera el nombre del catálogo actual de este objeto de conexión. (Traducción automática)

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

Devuelve una lista que contiene el nombre y el valor actual de cada propiedad de información del cliente compatible con el controlador. (Traducción automática)

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)

Devuelve el valor de la propiedad de información del cliente especificada por nombre. (Traducción automática)

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

Recupera la capacidad de retención actual de los objetos ResultSet creados utilizando este objeto Connection. (Traducción automática)

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

Recupera un objeto DatabaseMetaData que contiene metadatos sobre la base de datos a la que este objeto Connection representa una conexión. (Traducción automática)

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

Recupera la cantidad de milisegundos que el controlador esperará hasta que se complete una solicitud de base de datos. (Traducción automática)

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

Recupera el nombre de esquema actual de este objeto de conexión. (Traducción automática)

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

Recupera el nivel de aislamiento de transacción actual de este objeto de conexión. (Traducción automática)

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

Recupera el objeto Mapa asociado con este objeto Conexión. (Traducción automática)

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

Recupera la primera advertencia informada por las llamadas a este objeto Connection. (Traducción automática)

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

Recupera si este objeto de conexión se ha cerrado. (Traducción automática)

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

Recupera si este objeto de conexión está en modo de solo lectura. (Traducción automática)

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)

Devuelve verdadero si la conexión no se ha cerrado y aún es válida. (Traducción automática)

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)

Convierte la declaración SQL dada en la gramática SQL nativa del sistema. (Traducción automática)

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)

Crea un objeto CallableStatement para llamar a procedimientos almacenados de la base de datos. (Traducción automática)

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)

Crea un objeto CallableStatement que generará objetos ResultSet con el tipo y la simultaneidad indicados. (Traducción automática)

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)

Crea un objeto CallableStatement que generará objetos ResultSet con el tipo y la simultaneidad indicados. (Traducción automática)

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)

Crea un objeto PreparedStatement para enviar instrucciones SQL parametrizadas a la base de datos. (Traducción automática)

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)

Crea un objeto PreparedStatement predeterminado que tiene la capacidad de recuperar claves generadas automáticamente. (Traducción automática)

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)

Crea un objeto PreparedStatement predeterminado capaz de devolver las claves generadas automáticamente designadas por la matriz dada. (Traducción automática)

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)

Crea un objeto PreparedStatement que generará objetos ResultSet con el tipo y la simultaneidad indicados. (Traducción automática)

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)

Crea un objeto PreparedStatement que generará objetos ResultSet con el tipo, la simultaneidad y la capacidad de retención indicados. (Traducción automática)

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)

Crea un objeto PreparedStatement predeterminado capaz de devolver las claves generadas automáticamente designadas por la matriz dada. (Traducción automática)

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)

Elimina el punto de guardado especificado y los objetos de punto de guardado subsiguientes de la transacción actual. (Traducción automática)

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

Deshace todos los cambios realizados en la transacción actual y libera cualquier bloqueo de base de datos que tenga actualmente este objeto de conexión. (Traducción automática)

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)

Deshace todos los cambios realizados después de que se estableció el objeto de punto de guardado indicado. (Traducción automática)

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)

Establece el modo de confirmación automática de esta conexión en el estado indicado. (Traducción automática)

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)

Establece el nombre del catálogo dado para seleccionar un subespacio de la base de datos de este objeto Connection en el que trabajar. (Traducción automática)

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)

Establece el valor de la propiedad de información del cliente especificada por nombre en el valor especificado por valor. (Traducción automática)

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)

Establece el valor de las propiedades de información del cliente de la conexión. (Traducción automática)

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)

Cambia la capacidad de retención predeterminada de los objetos ResultSet creados utilizando este objeto Connection a la capacidad de retención indicada. (Traducción automática)

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)

Establece el período máximo que una conexión o los objetos creados a partir de la conexión esperarán a que la base de datos responda a cualquier solicitud. (Traducción automática)

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)

Pone esta conexión en modo de solo lectura como una sugerencia al controlador para habilitar las optimizaciones de la base de datos. (Traducción automática)

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

Crea un punto de guardado sin nombre en la transacción actual y devuelve el nuevo objeto de punto de guardado que lo representa. (Traducción automática)

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)

Crea un punto de guardado con el nombre dado en la transacción actual y devuelve el nuevo objeto de punto de guardado que lo representa. (Traducción automática)

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)

Establece el nombre del esquema dado para acceder. (Traducción automática)

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)

Especifica una clave de fragmentación para usar con esta conexión (Traducción automática)

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)

Especifica una shardingKey y una superShardingKey para usar con esta conexión (Traducción automática)

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)

Establece y valida la clave de fragmentación para esta conexión. (Traducción automática)

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)

Establece y valida las claves de fragmentación para esta conexión. (Traducción automática)

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)

Intenta cambiar el nivel de aislamiento de transacción para este objeto de conexión al indicado. (Traducción automática)

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)

Instala el objeto TypeMap dado como el mapa de tipos para este objeto Connection. (Traducción automática)

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

Consulte el siguiente enlace.


Related posts

To top of page