2008-02-08

看看老外怎么正常关闭JDBC的多个Statement

关键字: jdbc, statement

以前用JDBC处理多个Statement的时候,总会因为异常而无法完美的解决Statement正常关闭,今天无意看到老外写了以下一段代码,和大家分享一下:

 

private PreparedStatement psStmt1;
private PreparedStatement psStmt2;
private PreparedStatement psStmt3;
 
........................
........................

/*  关闭代码  */
public void cleanup() throws SQLException {
  SQLException exception = null;
  if (psStmt1 != null) {
    try {
      psStmt1.close();
    } catch (SQLException e) {
      exception = e;
    } finally {
      psStmt1 = null;
    }
  }
 
  if (psStmt2 != null) {
    try {
      psStmt2.close();
    } catch (SQLException e) {
      if (exception != null) e.setNextException(exception);
      exception = e;
    } finally {
      psStmt2 = null;
    }
  }
 
  if (psStmt3 != null) {
    try {
      psStmt3.close();
    } catch (SQLException e) {
      if (exception != null) e.setNextException(exception);
      exception = e;
    } finally {
      psStmt3 = null;
    }
  }
 
  if (exception != null) {
    throw exception;
  }
}

 

 

评论
bingshen01 2008-05-04
是啊
说说看法嘛
不要只是去踩
supttkl 2008-04-02
何必呢?
如果你向关闭直接
finally{
conn.close();
}
有空看看底层驱动怎么实现的。我用jtds驱动,到底层看了看,
如果该连接关闭,那么在关闭连接之前会关闭在此连接上打开的所有Statement,如果关闭Statement会关闭在此Statement上打开的所有ResultSet
qmy 2008-03-24
没看明白...啥意思?
pig345 2008-02-25
不怎么样。
ndzl 2008-02-16
老帖子真的是很棒啊。。。
受教了,多谢。。。
:D
weiqingfei 2008-02-14
ndzl 2008-02-13
这代码咋了?为啥被踩了三次?看不懂。。。
踩的人都是是高手吧,别把话说一半啊。。。说说哪不好嘛。。。
ruicoder 2008-02-12
难道,软件设计的真谛就是:最简章就是最好的 - -!!
hax 2008-02-09
这样的代码还有人顶?
发表评论

您还没有登录,请登录后发表评论

kyo100900
搜索本博客
最近加入圈子
存档
最新评论