ITeye博客

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

kyo100900 · 2008-02-08 11:40 · Database · Markdown

以前用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;
  }
}

评论(12)

  1. #12 楼 · TenAclock · 2011-11-15 12:33

    我是这样来释放

    
    /**
    	 * 合理的释放所有的用到的资源
    	 */
    	public static void free(){
    		try {
    			if(rs != null && !rs.isClosed()){
    				rs.close();
    			}
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}finally{
    			
    			try {
    				if(pstmt != null && !pstmt.isClosed()){
    					pstmt.close();
    				}
    			} catch (SQLException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    			
    			try {
    				if(connection != null && !connection.isClosed()){
    					connection.close();
    				}
    			} catch (SQLException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}
    	}
    
    
  2. #11 楼 · cooldh · 2009-05-25 14:34

    楼主说说 这样关闭有什么好处? 谢谢

  3. #10 楼 · sinokaka · 2008-05-20 08:47

    我估计楼主主要是赞赏这句话

    “ if (exception != null) e.setNextException(exception); ”

  4. #9 楼 · bingshen01 · 2008-05-04 13:35

    是啊 说说看法嘛 不要只是去踩

  5. #8 楼 · supttkl · 2008-04-02 08:20

    何必呢? 如果你向关闭直接 finally{ conn.close(); } 有空看看底层驱动怎么实现的。我用jtds驱动,到底层看了看, 如果该连接关闭,那么在关闭连接之前会关闭在此连接上打开的所有Statement,如果关闭Statement会关闭在此Statement上打开的所有ResultSet

  6. #7 楼 · qmy · 2008-03-24 13:40

    没看明白...啥意思?

  7. #6 楼 · pig345 · 2008-02-25 15:03

    不怎么样。

  8. #5 楼 · ndzl · 2008-02-16 12:48

    老帖子真的是很棒啊。。。 受教了,多谢。。。 :D

  9. #4 楼 · weiqingfei · 2008-02-14 09:31

    看下这个老帖子 http://www.iteye.com/post/80802

  10. #3 楼 · ndzl · 2008-02-13 22:34

    这代码咋了?为啥被踩了三次?看不懂。。。 踩的人都是是高手吧,别把话说一半啊。。。说说哪不好嘛。。。

  11. #2 楼 · ruicoder · 2008-02-12 16:27

    :o 难道,软件设计的真谛就是:最简章就是最好的 - -!!

  12. #1 楼 · hax · 2008-02-09 16:05

    这样的代码还有人顶?

评论功能维护中,当前仅展示历史评论。