【问题标题】:What is best way to fetch jdbc connection in sub method在子方法中获取 jdbc 连接的最佳方法是什么
【发布时间】:2013-08-12 07:22:03
【问题描述】:

我有关于在子方法中从池中获取 jdbc 连接的问题。以下是我遇到的两种方法,建议我使用哪种方法来避免连接泄漏并告诉我是否有其他解决方案。

方法一: getConnection 是返回 Connection 的方法。

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

方法二:

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

【问题讨论】:

    标签: java jdbc connection-pooling


    【解决方案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.
        }
    }
    

    【讨论】:

    • 感谢 Xabster。我面临很多连接泄漏问题,但在我的程序中,连接处处关闭。是否有标准方法来获取连接。
    • 是的,有一个相当标准的方法。它涉及到所谓的连接池,很多人推荐 BoneCP。我使用自己编写的池。
    • 但我使用的是 weblogic,我认为 bonecp 不支持 weblogic.any 替代方式。
    猜你喜欢
    • 2019-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多