接続が必要な場所は、接続を取得する必要があります。
リソースが「リーク」されないようにする方法は、Java 7 の try-with-resource 構文を使用することです。
public String fetchSomeData() {
try (Connection conn = getConnection()) { // This line, with this syntax, will ensure that it is automatically closed in an invisible "finally" block
// Do what you need to do with the data, return it or something else
} catch (SQLException e) {
// No need to do clean up here, log the exception or do whatever you want.
}
}
AutoCloseable インターフェイスを実装する任意のオブジェクトで try-with-resource 構文を使用できます。これには、接続、ステートメント、結果セットなどが含まれます。
トランザクションを実行する必要がある場合は、メソッドで Connection を初期化し、その Connection をトランザクションに追加する別のメソッドに渡し、それをコミットすることができます。その場合は、次のことができます。
public String fetchSomeDataInTransactionStyle() {
try (Connection conn = getConnection()) { // This line, with this syntax, will ensure that it is automatically closed in an invisible "finally" block
conn.setAutocommit(false);
addSomethingToTransaction(conn);
addSomethingMore(conn);
conn.commit();
} catch (SQLException e) {
// No need to do clean up here, log the exception or do whatever you want.
}
}