关闭连接以后发现连接不为空,这是为什么

在写JDBC查询的时候发现一个陌生的知识。执行这个程序以后发现输出结果竟然不为空,在网上查找以后发现自己并没有错,关闭数据库连接对象并不等于数据库连接对象为空。

close()操作关闭连接,但对它对连接引用没有任何作用。

通过使用Connection.close()我们可以关闭资源,并可以重用连接,因为它可以返回并存储到连接池中。
通过使Connection connection = null我们感觉到我们释放了连接资源,内存管理中没有泄漏,但是我们无法重用它。

	public void testQuery() {
		//数据库连接信息
		String url = "jdbc:mysql://localhost:3306/db_crm?useUnicode=true&characterEncoding=utf-8";
		String user = "root";
		String password = "root";
		
		Connection connection = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			Class.forName("com.mysql.jdbc.Driver");		
			connection = DriverManager.getConnection(url, user, password);
			String sql = "select * from tb_user";
			pstmt = connection.prepareStatement(sql);			
			rs = pstmt.executeQuery();
			
			while (rs.next()) {
				//1,2,3,4代表是第几列
				int id = rs.getInt(1);
				String username = rs.getString(2);
				String pwd = rs.getString(3);
				String email = rs.getString(4);
				//也可以使用列名来获取值
				String phone = rs.getString("phone");
				
				
				System.out.println("id:" + id + " " + "username: " + username + "pwd: " + pwd + " " + "email: " + email + "phone: " + phone);
			}
			
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (pstmt != null) {
					pstmt.close();
				}
				if (connection != null) {
					connection.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		
		System.out.println(rs);
		System.out.println(pstmt);
		System.out.println(connection);

	}

参考:connection.close()和connection=null之间的区别

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值