以前用JDBC处理多个Statement的时候,总会因为异常而无法完美的解决Statement正常关闭,今天无意看到老外写了以下一段代码,和大家分享一下:
- privatePreparedStatementpsStmt1;
- privatePreparedStatementpsStmt2;
- privatePreparedStatementpsStmt3;
- ........................
- ........................
- /*关闭代码*/
- publicvoidcleanup()throwsSQLException{
- SQLExceptionexception=null;
- if(psStmt1!=null){
- try{
- psStmt1.close();
- }catch(SQLExceptione){
- exception=e;
- }finally{
- psStmt1=null;
- }
- }
- if(psStmt2!=null){
- try{
- psStmt2.close();
- }catch(SQLExceptione){
- if(exception!=null)e.setNextException(exception);
- exception=e;
- }finally{
- psStmt2=null;
- }
- }
- if(psStmt3!=null){
- try{
- psStmt3.close();
- }catch(SQLExceptione){
- if(exception!=null)e.setNextException(exception);
- exception=e;
- }finally{
- psStmt3=null;
- }
- }
- if(exception!=null){
- throwexception;
- }
- }
别的方法
- /**
- *合理的释放所有的用到的资源
- */
- publicstaticvoidfree(){
- try{
- if(rs!=null&&!rs.isClosed()){
- rs.close();
- }
- }catch(SQLExceptione){
- //TODOAuto-generatedcatchblock
- e.printStackTrace();
- }finally{
- try{
- if(pstmt!=null&&!pstmt.isClosed()){
- pstmt.close();
- }
- }catch(SQLExceptione){
- //TODOAuto-generatedcatchblock
- e.printStackTrace();
- }
- try{
- if(connection!=null&&!connection.isClosed()){
- connection.close();
- }
- }catch(SQLExceptione){
- //TODOAuto-generatedcatchblock
- e.printStackTrace();
- }
- }
- }