怎么正常关闭JDBC的多个Statement

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

 

Java代码   收藏代码
  1. private PreparedStatement psStmt1;  
  2. private PreparedStatement psStmt2;  
  3. private PreparedStatement psStmt3;  
  4.    
  5. ........................  
  6. ........................  
  7.   
  8. /*  关闭代码  */  
  9. public void cleanup() throws SQLException {  
  10.   SQLException exception = null;  
  11.   if (psStmt1 != null) {  
  12.     try {  
  13.       psStmt1.close();  
  14.     } catch (SQLException e) {  
  15.       exception = e;  
  16.     } finally {  
  17.       psStmt1 = null;  
  18.     }  
  19.   }  
  20.    
  21.   if (psStmt2 != null) {  
  22.     try {  
  23.       psStmt2.close();  
  24.     } catch (SQLException e) {  
  25.       if (exception != null) e.setNextException(exception);  
  26.       exception = e;  
  27.     } finally {  
  28.       psStmt2 = null;  
  29.     }  
  30.   }  
  31.    
  32.   if (psStmt3 != null) {  
  33.     try {  
  34.       psStmt3.close();  
  35.     } catch (SQLException e) {  
  36.       if (exception != null) e.setNextException(exception);  
  37.       exception = e;  
  38.     } finally {  
  39.       psStmt3 = null;  
  40.     }  
  41.   }  
  42.    
  43.   if (exception != null) {  
  44.     throw exception;  
  45.   }  
  46. }  

 


别的方法

Java代码   收藏代码
  1. /** 
  2.      * 合理的释放所有的用到的资源 
  3.      */  
  4.     public static void free(){  
  5.         try {  
  6.             if(rs != null && !rs.isClosed()){  
  7.                 rs.close();  
  8.             }  
  9.         } catch (SQLException e) {  
  10.             // TODO Auto-generated catch block  
  11.             e.printStackTrace();  
  12.         }finally{  
  13.               
  14.             try {  
  15.                 if(pstmt != null && !pstmt.isClosed()){  
  16.                     pstmt.close();  
  17.                 }  
  18.             } catch (SQLException e) {  
  19.                 // TODO Auto-generated catch block  
  20.                 e.printStackTrace();  
  21.             }  
  22.               
  23.             try {  
  24.                 if(connection != null && !connection.isClosed()){  
  25.                     connection.close();  
  26.                 }  
  27.             } catch (SQLException e) {  
  28.                 // TODO Auto-generated catch block  
  29.                 e.printStackTrace();  
  30.             }  
  31.         }  
  32.     }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值