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