Write a SQLUtils class that contains static closeQuietly methods that catch and log such exceptions and then use them as needed.
You will get something like this:
public class SQLUtils { private static Log log = LogFactory.getLog(SQLUtils.class); public static void closeQuietly(Connection connection) { try { if (connection != null) { connection.close(); } } catch (SQLExcetpion e) { log.error("An error occurred closing connection.", e); } } public static void closeQuietly(Statement statement) { try { if (statement!= null) { statement.close(); } } catch (SQLExcetpion e) { log.error("An error occurred closing statement.", e); } } public static void closeQuietly(ResultSet resultSet) { try { if (resultSet!= null) { resultSet.close(); } } catch (SQLExcetpion e) { log.error("An error occurred closing result set.", e); } } }
And your client code will look something like this:
Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { connection = getConnection(); statement = connection.prepareStatement(...); resultSet = statement.executeQuery(); ... } finally { SQLUtils.closeQuietly(resultSet); SQLUtils.closeQuietly(statment); SQLUtils.closeQuietly(connection); }
Update: starting with Java 7, various JDBC interfaces extend java.lang.AutoCloseable and although the above code answers the original question, if you write code directly for the JDBC API, now it can be structured:
try ( Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(...); ResultSet resultSet = statement.executeQuery() ) { ... }
Nick Holt Aug 26 '09 at 16:06 2009-08-26 16:06
source share