【问题标题】:What's the correct way to handle SQL connection pool cleanup and error handling in Java?在 Java 中处理 SQL 连接池清理和错误处理的正确方法是什么?
【发布时间】:2013-04-10 00:27:09
【问题描述】:

我一直在学习如何使用 Oracle JDBC 在 Java 中使用 MySQL,并且我正在尝试进入 try/catch 和池清理的心态。

我想知道以下代码是否是完美清理所有内容的正确方法,或者您是否注意到我的代码中存在需要我遗漏的东西的漏洞。作为记录,我打算使用 InnoDB 及其行锁定机制,这就是我关闭自动提交的原因。

try
{
    connection = getConnection(); // obtains Connection from a pool

    connection.setAutoCommit(false);

    // do mysql stuff here
}
catch(SQLException e)
{
    if(connection != null)
    {
        try
        {
            connection.rollback(); // undo any changes
        }
        catch (SQLException e1)
        {
            this.trace(ExtensionLogLevel.ERROR, e1.getMessage());
        }
    }
}
finally
{
    if(connection != null)
    {
        try
        {
            if(!connection.isClosed())
            {
                connection.close(); // free up Connection so others using the connection pool can make use of this object
            }
        }
        catch (SQLException e)
        {
            this.trace(ExtensionLogLevel.ERROR, e.getMessage());
        }
    }
}

getConnection() 从池中返回一个 Connection 对象,connection.close() 将其关闭并将其释放回池中(所以有人告诉我,这仍然是新手,如果我说的是垃圾,请道歉)时间>。任何对此的帮助将不胜感激!

谢谢!

【问题讨论】:

  • 当您调用 Connection.close() 时,一个表现良好的连接池实现将为您完成所有必需的清理工作。

标签: java mysql jdbc innodb


【解决方案1】:

我建议不要在 finally 块中将 autocommit 设置回 true - 依赖 autocommit 设置为 true 的其他线程不应假定池中的连接处于此状态,而是应将 autocommit 设置为 true在使用连接之前(就像这个线程将 autocommit 设置为 false)。

此外,您应该在调用 close() 之前检查连接的 isClosed 属性。

除此之外,我没有发现任何问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 2021-12-16
    • 1970-01-01
    • 2017-09-20
    • 2011-06-22
    • 2013-08-18
    相关资源
    最近更新 更多