当Statement,ResultSet抛出错误之后,他是否会自动关闭?还是要手动关闭?

wuguix 2006-03-14 09:46:01
第一种写法
public void getit(Connection con,String id)throws Exception
{
String sql="select * from .. where id="+id;
Statement sm = conn.createStatement();
ResultSet rs = sm.executeQuery(sql);
if(rs.next){
System.out.print(rs.getString(2));
}
if(rs!=null)
rs.close();
rs=null;
if(sm!=null)
sm.close();
sm=null;
}


第二种写法
public void getit(Connection con,String id)throws Exception
{
Statement sm =null;
ResultSet rs=null;
String sql="select * from .. where id="+id;
try{
sm = conn.createStatement();
rs = sm.executeQuery(sql);
if(rs.next){
System.out.print(rs.getString(2));
}

}catch(Exception e){
throw new Exception(e);
}finally{
if(rs!=null)
rs.close();
rs=null;
if(sm!=null)
sm.close();
sm=null;
}
}
第二种写法比较安全,但是他会影响性能。
...全文
180 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
wuguix 2006-03-15
  • 打赏
  • 举报
回复
更正!

关系==关闭
wuguix 2006-03-15
  • 打赏
  • 举报
回复
因为捕获错误再抛出会影响性能,
但是如果resultset 或者statement 自身在出现错误的时候能自行关系,那使用第一种写法更好。是不是?
yxxx 2006-03-14
  • 打赏
  • 举报
回复
楼主说会怎么影响性能?
aylian 2006-03-14
  • 打赏
  • 举报
回复
第二种写法为JAVA的推荐写法,我觉得没什么问题,不知道楼主为什么说会影响性能?
wuguix 2006-03-14
  • 打赏
  • 举报
回复
mm
wuguix 2006-03-14
  • 打赏
  • 举报
回复
大家都来发表一下观点啊。
wangx1949 2006-03-14
  • 打赏
  • 举报
回复
第二种方法好,Statement,ResultSet如果不关闭,可能引起内存泄漏,这样麻烦更大.
wuguix 2006-03-14
  • 打赏
  • 举报
回复
当然了,如果你把错误不抛出来,调用你方法的程序怎么捕获异常?
螃蟹k3179 2006-03-14
  • 打赏
  • 举报
回复
public void getit(Connection con,String id)
{
Statement sm =null;
ResultSet rs=null;
String sql="select * from .. where id="+id;
try{
sm = conn.createStatement();
rs = sm.executeQuery(sql);
if(rs.next){
System.out.print(rs.getString(2));
}

}catch(Exception e){
e.printStack();
}finally{
if(rs!=null)
rs.close();
rs=null;
if(sm!=null)
sm.close();
sm=null;
}
}
这么写不好吗

81,091

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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