zoukankan      html  css  js  c++  java
  • JDBC:Connection.close()

    https://www.2cto.com/database/201501/369246.html

    Connection对象在执行close() 方法之后,并不是直接把Connection对象设置为null (Connection对象有一个方法, isClosed() 判断Connection是否被关闭,如果直接设置为null,再执行isClosed() 就会报空指针异常)

    close()源码:

    public void close() throws SQLException {
        synchronized (getConnectionMutex()) {
            if (this.connectionLifecycleInterceptors != null) {
                new IterateBlock<Extension>(this.connectionLifecycleInterceptors.iterator()) {
                    @Override
                    void forEach(Extension each) throws SQLException {
                        ((ConnectionLifecycleInterceptor) each).close();
                    }
                }.doForAll();
            }
    
            realClose(true, true, false, null);
        }
    }

    测试代码:

    DBUtil是自己写的一个工具类,有静态方法 ResultSet generalQuery(),静态属性conn, pst 

    public class Test {
        public static void main(String[] args) {
            String sql = "select * from member where mId = ? and mPwd = ?";
            Object[] params = {"2015", "1233"};
            ResultSet rs = DBUtil.generalQuery(sql, params);int cnt = 0;
            try {
                if(rs != null) {
                    rs.last();
                    cnt = rs.getRow();
                }
                if(rs != null) rs.close();
                if(DBUtil.pst != null) DBUtil.pst.close();
                if(DBUtil.conn != null) DBUtil.conn.close();
                
                if(cnt != 0) {
                    System.out.println("查询成功!");
                }else {
                    System.out.println("查询失败");
                }
            }catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                System.out.println(DBUtil.conn);  // com.mysql.jdbc.JDBC4Connection@619a5dff
                System.out.println(DBUtil.pst);   // java.sql.SQLException: No operations allowed after statement closed.
                System.out.println(rs); //com.mysql.jdbc.JDBC42ResultSet@23ab930d
                
                System.out.println(DBUtil.conn.isClosed());  //true
                System.out.println(DBUtil.pst.isClosed());  //true
                System.out.println(rs.isClosed()); //true
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
  • 相关阅读:
    php 内置的 webserver 研究。
    php 系列
    git 以及 github 使用系列
    中午和同事聊天,了解的一点网络方面的东西。
    javascript中0.01*2324=23.240000000000002 ?
    javascript的 replace() 方法的使用讲解
    PHP中的ORM
    javascript 函数 add(1)(2)(3)(4)实现无限极累加 —— 一步一步原理解析
    animate.css
    面向对象编程
  • 原文地址:https://www.cnblogs.com/DDiamondd/p/11072961.html
Copyright © 2011-2022 走看看