从零开始学JDBC--1.10 资源释放代码的优化

来源:互联网 发布:厦门大学网络远程教育 编辑:程序博客网 时间:2024/05/16 16:08


在资源释放的时候,我们之前只是将资源进行了关闭,但是该对象还是在内存中保持,并没有立即被收回,所以要告知虚拟机这个对象需要被收回,将这个对象的引用置为null

建议资源释放使用如下的写法:

    public static void closeAll(Connection conn, CallableStatement stmt, ResultSet rs) {        try{            if (rs != null) {                rs.close();                rs = null;            }            if (stmt != null) {                stmt.close();                stmt = null;            }            if (conn != null && conn.isClosed()) {                conn.close();                conn = null;            }         }   catch (SQLException e) {                e.printStackTrace();                throw new RuntimeException(e);        }    }

快速捕获异常的快捷键:Alt+shift+z

0 0
原创粉丝点击