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(); } } }