Java : Connection (JDBC) - API使用例
Connection (Java SE 21 & JDK 21) の使い方まとめです。
だいたいのメソッドを網羅済みです。
API仕様書のおともにどうぞ。
概要
Connection インタフェースは、特定のデータベースとの接続(セッション) を表します。
このインタフェースをとおして、SQL文やストアド・プロシージャを実行できます。
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);
}
}
}
// 結果
// ↓
//-- create table --
//ret = 0
//-- insert --
//ret = 1
//ret = 1
//ret = 1
//-- select --
//Orange : 10
//Banana : 20
//Apple : 30
}
本記事のコード例では、利便性のために下記の Product クラスと ProductTable クラスを使います。
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;
}
}
フィールド
static final int TRANSACTION_NONE
System.out.println(Connection.TRANSACTION_NONE); // 0
※ Derby はこのフィールドをサポートしていません。
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);
}
// 結果
// ↓
//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
System.out.println(Connection.TRANSACTION_READ_COMMITTED); // 2
// ノンリピータブルリードを発生させる例です。
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);
// テーブルを準備します。
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);
}
});
}
// 結果
// ↓
//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
System.out.println(Connection.TRANSACTION_READ_UNCOMMITTED); // 1
// ダーティリードを発生させる例です。
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);
// テーブルを準備します。
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);
}
});
}
// 結果
// ↓
//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
System.out.println(Connection.TRANSACTION_REPEATABLE_READ); // 4
// ファントムリードを発生させる例です。
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);
// テーブルを準備します。
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);
}
});
}
// 結果
// ↓
//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
System.out.println(Connection.TRANSACTION_SERIALIZABLE); // 8
// ファントムリードが発生しない例です。
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);
// テーブルを準備します。
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);
}
});
}
// 結果
// ↓
//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 **
メソッド
void abort (Executor executor)
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)]
// コミットしません。
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 ()
このメソッドは、接続プール・マネージャで使用されます。
ユーザがこのメソッドを使うことは少ないと思いますので、コード例は割愛します。
void clearWarnings ()
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 ()
final var url = "jdbc:derby:memory:db;create=true";
try (final var connection = DriverManager.getConnection(url)) {
System.out.println(connection.isClosed()); // false
}
// try-with-resources文を使わない例です。
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 ()
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)]
// コミットしません。
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)
※ Derby はこのメソッドをサポートしていません。
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);
}
// 結果
// ↓
//java.sql.SQLFeatureNotSupportedException: Feature not implemented: No details.
Blob createBlob ()
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));
}
}
}
// 結果
// ↓
//value = [10, 20, 30]
}
Clob createClob ()
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);
}
}
}
// 結果
// ↓
//value = XYZ
}
NClob createNClob ()
※ Derby はこのメソッドをサポートしていません。
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);
}
// 結果
// ↓
//java.sql.SQLFeatureNotSupportedException: Feature not implemented: No details.
SQLXML createSQLXML ()
※ Derby はこのメソッドをサポートしていません。
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);
}
// 結果
// ↓
//java.sql.SQLFeatureNotSupportedException: Feature not implemented: No details.
Statement createStatement ()
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);
}
}
}
// 結果
// ↓
//-- create table --
//ret = 0
//-- insert --
//ret = 1
//ret = 1
//ret = 1
//-- select --
//Orange : 10
//Banana : 20
//Apple : 30
}
Statement createStatement (int resultSetType, int resultSetConcurrency)
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();
}
}
}
// 結果
// ↓
//-- 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);
}
}
}
// 結果
// ↓
//-- select --
//Apple : 15
//Banana : 10
//Orange : 5
}
Statement createStatement (int resultSetType, int resultSetConcurrency, int resultSetHoldability)
関連 : 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)
※ Derby はこのメソッドをサポートしていません。
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);
}
// 結果
// ↓
//java.sql.SQLFeatureNotSupportedException: Feature not implemented: No details.
default void endRequest ()
このメソッドは、接続プール・マネージャで使用されます。
ユーザがこのメソッドを使うことは少ないと思いますので、コード例は割愛します。
boolean getAutoCommit ()
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)]
// コミットしません。
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 ()
※ Derby はこのメソッドをサポートしていません。
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 ()
※ Derby はこのメソッドをサポートしていません。
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);
}
// 結果
// ↓
//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);
}
// 結果
// ↓
//java.sql.SQLClientInfoException:
// The requested property change is not supported 'aaa'='XXX'.
}
String getClientInfo (String name)
※ Derby はこのメソッドをサポートしていません。
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);
}
// 結果
// ↓
//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);
}
// 結果
// ↓
//java.sql.SQLClientInfoException:
// The requested property change is not supported 'aaa'='XXX'.
}
int getHoldability ()
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 ()
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 ()
※ Derby はこのメソッドをサポートしていません。
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!");
}
// 結果
// ↓
//SQLFeatureNotSupportedException!
String getSchema ()
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 ()
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 ()
※ Derby はこのメソッドをサポートしていません。
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);
}
// 結果
// ↓
//java.sql.SQLFeatureNotSupportedException: Feature not implemented: No details.
}
SQLWarning getWarnings ()
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 ()
final var url = "jdbc:derby:memory:db;create=true";
try (final var connection = DriverManager.getConnection(url)) {
System.out.println(connection.isClosed()); // false
}
// try-with-resources文を使わない例です。
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 ()
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);
}
// 結果
// ↓
//java.sql.SQLException: An SQL data change is not permitted
// for a read-only connection, user or database.
}
boolean isValid (int timeout)
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)
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)
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)
関連 : 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)
関連 : 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)
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);
}
}
}
// 結果
// ↓
//-- create table --
//ret = 0
//-- insert --
//ret = 1
//ret = 1
//ret = 1
//-- select --
//Orange : 10
//Banana : 20
//Apple : 30
}
PreparedStatement prepareStatement (String sql, int autoGeneratedKeys)
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);
}
}
}
// 結果
// ↓
//-- 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)
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);
}
}
}
// 結果
// ↓
//-- 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)
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();
}
}
}
// 結果
// ↓
//-- 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);
}
}
}
// 結果
// ↓
//-- select --
//Apple : 15
//Banana : 10
//Orange : 5
}
PreparedStatement prepareStatement (String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability)
関連 : 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)
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);
}
}
}
// 結果
// ↓
//-- 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)
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)]
// コミットしません。
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();
}
// 結果
// ↓
//java.sql.SQLException: SAVEPOINT,
// SAVEPT1 does not exist or is not active in the current transaction.
}
void rollback ()
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)]
// コミットしません。
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)
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)]
// コミットしません。
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)
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)]
// コミットしません。
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)
※ Derby はこのメソッドをサポートしていません。
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)
※ Derby はこのメソッドをサポートしていません。
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);
}
// 結果
// ↓
//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);
}
// 結果
// ↓
//java.sql.SQLClientInfoException:
// The requested property change is not supported 'aaa'='XXX'.
}
void setClientInfo (Properties properties)
※ Derby はこのメソッドをサポートしていません。
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);
}
// 結果
// ↓
//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);
}
// 結果
// ↓
//java.sql.SQLClientInfoException:
// The requested property change is not supported 'aaa'='XXX'.
}
void setHoldability (int 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)
※ Derby はこのメソッドをサポートしていません。
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!");
}
// 結果
// ↓
//SQLFeatureNotSupportedException!
}
void setReadOnly (boolean readOnly)
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);
}
// 結果
// ↓
//java.sql.SQLException: An SQL data change is not permitted
// for a read-only connection, user or database.
}
Savepoint setSavepoint ()
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)]
// コミットしません。
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)
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)]
// コミットしません。
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)
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)
※ Derby はこのメソッドをサポートしていません。
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);
}
// 結果
// ↓
//java.sql.SQLFeatureNotSupportedException: setShardingKey not implemented
default void setShardingKey (ShardingKey shardingKey, ShardingKey superShardingKey)
※ Derby はこのメソッドをサポートしていません。
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);
}
// 結果
// ↓
//java.sql.SQLFeatureNotSupportedException: setShardingKey not implemented
default boolean setShardingKeyIfValid (ShardingKey shardingKey, int timeout)
※ Derby はこのメソッドをサポートしていません。
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);
}
// 結果
// ↓
//java.sql.SQLFeatureNotSupportedException: setShardingKeyIfValid not implemented
default boolean setShardingKeyIfValid (ShardingKey shardingKey, ShardingKey superShardingKey, int timeout)
※ Derby はこのメソッドをサポートしていません。
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);
}
// 結果
// ↓
//java.sql.SQLFeatureNotSupportedException: setShardingKeyIfValid not implemented
void setTransactionIsolation (int 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
}
void setTypeMap (Map<String,Class<?>> map)
※ Derby はこのメソッドをサポートしていません。
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);
}
// 結果
// ↓
//java.sql.SQLFeatureNotSupportedException: Feature not implemented: No details.
}
Wrapperで宣言されたメソッド
isWrapperFor, unwrap
「Java API 使用例 : Wrapper」をご参照ください。
関連記事
- API 使用例