Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Closing several JDBC statements cleanly

DZone's Guide to

Closing several JDBC statements cleanly

· Database Zone
Free Resource

Running out of memory? Learn how Redis Enterprise enables large dataset analysis with the highest throughput and lowest latency while reducing costs over 75%! 

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;
  }
}

Running out of memory? Never run out of memory with Redis Enterprise databaseStart your free trial today.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}