preparedStatement和ResultSet用完必须要close()吗?

guan_tu 2013-10-21 10:22:33

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所指向的对象一直不会关闭,占用着资源呢?
...全文
4293 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
无聊找乐 2013-10-21
  • 打赏
  • 举报
回复
引用 3 楼 rainbowsix 的回复:
这种东西看看官方文档的说明就很清楚了。 close void 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.
手动调用close是个好的时间,这样能更快的释放资源。
无聊找乐 2013-10-21
  • 打赏
  • 举报
回复 1
这种东西看看官方文档的说明就很清楚了。 close void 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.
异常人生 2013-10-21
  • 打赏
  • 举报
回复
引用 1 楼 huxiweng 的回复:
请问我在下一次使用之前必须调用close()方法吗? re:不用。 如果我没有调用的话,是不是之前pstmt 和rs所指向的对象一直不会关闭,占用着资源呢? re:不会一直不关闭的,gc(垃圾回收器)会去处理它的,注意用完conn,要close掉就行了
正解,但是建议最好还是每次用完之后关闭
teemai 2013-10-21
  • 打赏
  • 举报
回复
请问我在下一次使用之前必须调用close()方法吗? re:不用。 如果我没有调用的话,是不是之前pstmt 和rs所指向的对象一直不会关闭,占用着资源呢? re:不会一直不关闭的,gc(垃圾回收器)会去处理它的,注意用完conn,要close掉就行了

67,541

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧