public class Test1{
public static void main(String[] args) throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:sjbitdb","epet","bdqn");
PreparedStatement pstmt=conn.prepareStatement("select count(*) from student");
ResultSet rs=pstmt.executeQuery();
while (rs.next()) {
int num=rs.getInt(1);
System.out.println("共有"+num+"名学生!");
}
pstmt=conn.prepareStatement("select * from Student");//当重新给pstmt赋值时,之前的pstmt需要手动调用pstmt.close()方法吗
rs=pstmt.executeQuery();
while (rs.next()) {
int id=rs.getInt(1);
String name=rs.getString(2);
System.out.println("序号"+id+"\t姓名"+name);
}
pstmt.close();
conn.close();
}
}
上面这段代码,分别使用pstmt和rs进行了两次不同的操作,我代码最后关闭的肯定是最后一次pstmt 和rs所指向的对象,但是我之前pstmt和rs所指向的对象并没有调用对应的close()方法,请问我在下一次使用之前必须调用close()方法吗?如果我没有调用的话,是不是之前pstmt 和rs所指向的对象一直不会关闭,占用着资源呢?

解决方案 »

  1.   

    请问我在下一次使用之前必须调用close()方法吗?
    re:不用。
    如果我没有调用的话,是不是之前pstmt 和rs所指向的对象一直不会关闭,占用着资源呢?
    re:不会一直不关闭的,gc(垃圾回收器)会去处理它的,注意用完conn,要close掉就行了
      

  2.   

    这种东西看看官方文档的说明就很清楚了。closevoid close()
               throws SQLException
    Releases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed. It is generally good practice  to release resources as soon as you are finished with them to avoid tying up database resources.
      

  3.   

    手动调用close是个好的时间,这样能更快的释放资源。