gpt4 book ai didi

java - 正确关闭 JDBC 连接对象

转载 作者:行者123 更新时间:2023-12-01 18:07:37 25 4
gpt4 key购买 nike

据我了解,关闭finally block 中的连接对象是最佳实践。但是,如果 rs.close()/ps.close() 在finally block 中抛出异常,则不会执行 conn.close() 。因此,我曾经在两个位置关闭连接(如提供的示例中所示),一次是在使用后直接关闭,其次是在finally block 中使用空检查来关闭连接。但有些人认为 block 1 是冗余代码。它真的是多余的还是有正确的方法来解决这个问题而不关闭两个地方的连接?

Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = dataSource.getConnection(); // geting the connection object
ps = connection.prepareStatement(INSERT_QUERY);
rs = ps.executeQuery();
// some logic here ...
// ---- block 1 ----
ps.close()
ps = null;
rs.close();
rs = null;
conn.close();
conn = null;
// ---- end block 1 ----
} catch (SQLException e) {
// exception handling ...
} finally {
closeQuietly(conn, ps, rs);
}

private void closeQuietly(Connection connection, PreparedStatement ps, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {}
}
}

最佳答案

is there proper way to address this issue without closing the connection in two places?

是的:

try (Connection conn = dataSource.getConnection(); // geting the connection object
Prepared Statement ps = connection.prepareStatement(INSERT_QUERY);
ResultSet rs = ps.executeQuery();) {
// ...
}

这是“try-with-resources”语法。 try 之后 () 内声明的所有内容都保证被关闭。

关于java - 正确关闭 JDBC 连接对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35122831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com