Platinum Partner
sql

Closing several JDBC statements cleanly

It's been a while since I wrote some raw JDBC code. I didn't remember that it was so tedious to manually close a series of PreparedStatement objects and make sure that any exception was properly handled and reported.

Note that the ARM blocks or BGGA closures proposals don't make this easier since this cleanup should be done after the prepared statements have been used for a while in various other methods, it doesn't automatically have to be done at the end of a lexical scope.

This is what I came up with.

Of course, you could write an alternative implementation that creates some kind of repository for the prepared statements in a map and then provide a method that closes them all by going over the entries of the map while preserving the exceptions in a similar manner. Any other suggestions or comments for this to be done better?

private PreparedStatement psStmt1;
private PreparedStatement psStmt2;
private PreparedStatement psStmt3;
 
public void cleanup() throws SQLException {
  SQLException exception = null;
  if (psStmt1 != null) {
    try {
      psStmt1.close();
    } catch (SQLException e) {
      exception = e;
    } finally {
      psStmt1 = null;
    }
  }
 
  if (psStmt2 != null) {
    try {
      psStmt2.close();
    } catch (SQLException e) {
      if (exception != null) e.setNextException(exception);
      exception = e;
    } finally {
      psStmt2 = null;
    }
  }
 
  if (psStmt3 != null) {
    try {
      psStmt3.close();
    } catch (SQLException e) {
      if (exception != null) e.setNextException(exception);
      exception = e;
    } finally {
      psStmt3 = null;
    }
  }
 
  if (exception != null) {
    throw exception;
  }
}
{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}