How to properly clean up JDBC resources in Java?

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

    As others have pointed out, JDBC resources (statements, result sets, etc...) are rarely null. If they are, you have bigger issues on your hands than NullPointerExceptions. In that regard, the NullPointerExceptions will help alert you to severe problems with your JDBC driver. The typical checking for null before calling close() would silently hide the problem if your JDBC driver was, in fact, providing you with null references.

    As well, not all JDBC drivers follow the specification precisely. For example, some drivers will not automatically close a ResultSet when it's associated Statement is closed. Therefore, you have to ensure that you explicitly close both the ResultSet and its Statement (sigh).

    In practice, I have found this technique useful (although its not the prettiest):

    PreparedStatement statement = connection.prepareStatement("...");
    try {
        ResultSet results = statement.executeQuery();
        try {
            while (results.next()) {
                // ...
            }
        } finally {
            results.close();
        }
    } finally {
        statement.close();
    }
    

    This technique guarantees that every close() statement is executed, starting with the ResultSet and working its way outward. NullPointerExceptions are still thrown should the driver provide you with null references, but I allow this for the reasons explained at the beginning. SQLExceptions are still thrown if any of the close() statements fail (I consider this a good thing - I want to know if something is going wrong).

提交回复
热议问题