【问题标题】:Cannot close Oracle connection from WebSphere datasource无法关闭来自 WebSphere 数据源的 Oracle 连接
【发布时间】:2015-10-10 21:32:27
【问题描述】:

我尝试连接到 Oracle 数据库(检查连接状态)。我正在使用以下代码,效果很好。

public String getDatabaseStatus() {
    Connection conn;
    try {
        conn = DriverManager.getConnection( "jdbc:oracle:thin:@192.168.0.70:1521:XE", "foo","bar");
        conn.close();
    } catch (Exception e) {
        return "ERR - " + e.getMessage();
    }
    return "Connection succesful";
}

但是,当使用 Websphere 数据源时,在 10 次(连接限制)刷新后页面会挂起。代码:

public String getDatabaseStatus() {
    Connection conn;
    try {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("jdbc/xe");
        conn = WSCallHelper.getNativeConnection(ds.getConnection());
    } catch (Exception e) {
        return "ERR - " + e.getMessage();
    }
    return "Connection succesful";
}

我试图关闭提供的连接,但它给了我错误:

J2CA0206W - 发生连接错误。为了帮助确定问题,请在连接工厂或数据源上启用诊断连接使用选项。这是多线程访问检测选项。或者检查 Database 或 MessageProvider 是否可用。

任何帮助将不胜感激。

【问题讨论】:

  • WSCallHelper.getNativeConnection(...) 是做什么的?
  • 我可以通过这种方式获得本地 Oracle 连接。我需要这个来从 Oracle 函数中获取结果; OracleCallableStatement 是接收到的对象类型。

标签: oracle jakarta-ee jdbc websphere datasource


【解决方案1】:

您必须关闭从数据源收到的连接:

public String getDatabaseStatus() {
    Connection conn;
    try {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("jdbc/xe");
        java.sql.Connection connection = ds.getConnection();
        try {
            conn = WSCallHelper.getNativeConnection(connection);
        } finally {
            safeClose(connection);
        }
    } catch (Exception e) {
        return "ERR - " + e.getMessage();
    }
    return "Connection succesful";
}

private void safeClose(java.sql.Connection connection) {
    try {
        connection.close();
    } catch (SQLException e) {
        log.warn("Failed to close database connection", e);
    }
}

如果您使用的是 Java 7 或更高版本,您可以将其简化为:

public String getDatabaseStatus() {
    Connection conn;
    try {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("jdbc/xe");
        try (java.sql.Connection connection = ds.getConnection()) {
            conn = WSCallHelper.getNativeConnection(connection);
        }
    } catch (Exception e) {
        return "ERR - " + e.getMessage();
    }
    return "Connection succesful";
}

如果您不这样做,您的连接将不会返回到池中,并且您将用完连接。

【讨论】:

  • 好的,我会尝试第二种方法并报告结果。但正如我所写,我每次都收到 J2CA0206W 错误。
  • 在第二个代码示例中,您获得了 2 个连接并且没有关闭第一个连接,这将在每次调用该方法时泄漏一个连接。假设这只是一个错字
猜你喜欢
  • 2011-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-11
  • 2021-10-17
  • 2011-03-13
  • 1970-01-01
  • 2022-01-23
相关资源
最近更新 更多