0

サブメソッドでプールからjdbc接続をフェッチすることについて質問があります。以下は、接続のリークを回避するのに最適な方法を提案し、他の解決策があるかどうかを示す2つの方法です。

方法 1: getConnectionを返す方法Connectionです。

void testMain(){
    Connection conn = getConnection();
    subMethod(conn)
    conn.close();
}
void subMethod(connection conn){
    // use jdbc connection
    return;
}

方法 2:

void testMain(){
    Connection conn = getConnection();
    subMethod()
    conn.close();
}
void subMethod(){
    Connection conn = getConnection();
    conn.close();
    return;
}
4

1 に答える 1

1

接続が必要な場所は、接続を取得する必要があります。

リソースが「リーク」されないようにする方法は、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.
    }
}
于 2013-08-10T13:33:32.613 に答える