java - 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 变量。
解决方案
好吧,我解决了我的问题,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
}
}
}
}
推荐阅读
- java - 我应该编写自定义验证还是正确配置弹簧?
- acceleo - 3.7.x 版的 Acceleo 编译器(.mtl 到 .emtl)
- excel - 是否可以将数学文本放入 Excel 中?
- latex - 如何在 Sphinx 生成的 Latex 文档中添加版权声明?
- symfony - Symfony 4 - 如何为存在路由的 Web api REST 修复“404 Not Found”?
- python - 从带有其他数字的地址字符串中获取印度邮政编码
- python - 无法更新 Django 内置用户的 last_login 字段
- python - 如何使python中的函数超时
- c# - 使用 GetCurrentDirectory 函数获取同一位置的两个不同值
- android - StackNavigator 标题内的 DrawerNavigator