How to properly clean up JDBC resources in Java?

后端 未结 9 1966
说谎
说谎 2020-12-16 03:17

What is considered best practices when cleaning up JDBC resources and why? I kept the example short, thus just the cleaning up of the ResultSet.

finally
{
          


        
9条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-16 03:53

    I see no problem with your second (uncommon) version.

    • usually, rs will not be null, so an NPE will occur in rare cases. So I see no performance problem here.
    • both version behave exactly the same in case of rs = null

    The only disadvantage - if we have more then one resource to close, then we'd have to add one try/catch for each resource, if we want to close as many resources as possible. Otherwise, we'd enter the catch clause with the first null and that could cause undiscored leaks.

    So it would look like that:

    finally {
       try{rs.close();  }catch(Exception ignored){}
       try{stmt.close();}catch(Exception ignored){}
       try{conn.close();}catch(Exception ignored){}
    }
    

    ... which is still readable and understandable. But, according to never change a common pattern - I'd stick to the old-fashioned way of testing null first and catching SQLException while closing.

提交回复
热议问题