在写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);
}