How to properly clean up JDBC resources in Java?

后端 未结 9 1965
说谎
说谎 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:49

    I tend to use the following approach. I think it is good to check for null because it shows your intent i.e. that you do realise that these objects could be null in rare cases. (A null check is also faster than the creation of a NullPointerException.) I also think it is good to log the exceptions, instead of swallowing them. In the cases where close fails, I want to know about it and have it in my log files.

    finally {            
                if (rs != null) {
                    try {
                        rs.close();
                    } catch (SQLException e) {
                     LOG.warn("Failed to close rs", e);
                    }
                }
                if (st != null) {
                    try {
                        st.close();
                    } catch (SQLException e) { 
                     LOG.warn("Failed to close st", e);     
                    }
                }
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (SQLException e) {
                     LOG.warn("Failed to close conn", e);
                    }
                }
            }
    

    If you are going to be doing this frequently, instead of copying and pasting this code over and over again, create a utility class with static methods to close the ResultSet, Statement and Connection.

    With DBUtils you can perform this cleanup quite concisely as follows:

     finally {            
                DBUtils.closeQuietly(rs);
                DBUtils.closeQuietly(st);
                DBUtils.closeQuietly(conn);            
            }
    

提交回复
热议问题