使用完之后
Connection,你需要通过调用其
close()方法显式关闭它,以释放连接可能会保留的任何其他数据库资源(光标,句柄等)。
实际上,Java中的安全模式是在完成对
ResultSet,,
Statement和
Connection(按顺序)关闭后的代码finally块,如下所示:
Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;try { // Do stuff ...} catch (SQLException ex) { // Exception handling stuff ...} finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { } } if (ps != null) { try { ps.close(); } catch (SQLException e) { } } if (conn != null) { try { conn.close(); } catch (SQLException e) { } }}该finally块可以稍作改进(以避免空检查):
} finally { try { rs.close(); } catch (Exception e) { } try { ps.close(); } catch (Exception e) { } try { conn.close(); } catch (Exception e) { }}但是,这仍然是非常冗长的,因此你通常最终使用helper类在null安全的helper方法中关闭对象,并且该finally块变为类似以下内容:
} finally { DbUtils.closeQuietly(rs); DbUtils.closeQuietly(ps); DbUtils.closeQuietly(conn);}而且,实际上,Apache Commons DbUtils有一个DbUtils正是在执行该操作的类,因此无需编写你自己的类。



