首页 > 解决方案 > Fortify:无法释放数据库资源

问题描述

我正在尝试使用 fortify 查看我的代码的漏洞。报告说我有一个问题,说“该函数有时无法释放分配的数据库资源”。这是代码以及问题所在的行。我试图在 finally 块中关闭连接,但它不能解决问题。如何解决这个问题?

private AnotherService anotherService;

private void create() {
    Connection conn = null;
    try {
        conn = getCon(); // With fortify, there's an issue which said "the function sometimes fails to release a database resource allocated by", and it refers to this line
        conn.setAutoCommit(false);
        anotherService.myFunction(conn);
        // the conn.commit() is inside anotherService, because I have to make one connection
        // rest of code

    } catch (Exception e) {
        e.printStackTrace;
        if (null != conn) {
            conn.rollback();
        }
    } finally {
        if (null != conn) {
            conn.close();
        }
    }
}

private static Connection getCon() {
    Connection connection = null;
        try {
            Class.forName("org.postgresql.Driver");
            connection = DriverManager.getConnection(
                    "jdbc:postgresql://localhost:5432/dbname",
                    "username",
                    "password");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    return connection;
}

另外:如果我使用 try-with-resource (像这样try (Connection conn = getCon())来自动关闭东西,如果发生任何异常,我如何在 catch 块中调用 conn.rollback() ?由于在 try-with-resources 中声明了 conn 变量。

标签: javafortify

解决方案


好吧,我解决了我的问题,close 方法应该在 finally 块中的 try-catch 内调用,如链接中所述。

如果链接断开,这是我用来解决问题的代码:

Statement stmt = null;
ResultSet rs = null;
Connection conn = getConnection();
try {
  stmt = conn.createStatement();
  rs = stmt.executeQuery(sqlQuery);
  processResults(rs);
} catch (SQLException e) {
  // Forward to handler
} finally {
  try {
    if (rs != null) {rs.close();}
  } catch (SQLException e) {
    // Forward to handler
  } finally {
    try {
      if (stmt != null) {stmt.close();}
    } catch (SQLException e) {
      // Forward to handler
    } finally {
      try {
        if (conn != null) {conn.close();}
      } catch (SQLException e) {
        // Forward to handler
      }
    }
  }
}

推荐阅读