I'm working on a Java application that conducts numerous JDBC queries to a database, each specified in a separate method with roughly the following format.
public static void sampleJDBCQuery(String query, DBUtil dbUtil, DataStructure dataStructure) {
ResultSet rs = null;
Handle handle = null;
Connection conn = null;
Statement stmt = null;
LOGGER.debug("Executing query = {}", query);
try {
handle = dbUtil.getConnectionHandle();
conn = handle.getConnection();
if (conn != null) {
stmt = conn.createStatement();
if (stmt != null) {
rs = stmt.executeQuery(query);
if (rs != null) {
while (rs.next()) {
// populate dataStructure using rs
}
}
}
}
} catch (Exception e) {
Metrics.markMeter("vertica.read.error");
LOGGER.error(e.getMessage(), e);
} finally {
DBUtil.closeResultSet(rs);
DBUtil.closeStatement(stmt);
DBUtil.close(handle);
LOGGER.debug("Finished query = {}", query);
}
}
With many different sample queries (and data structure classes) of the format above, my code base has been growing substantially. My aim is to have a helper method that abstracts away most of this JDBC logic for me. My first thought was to have a method with the following signature.
public static ResultSet executeJDBCQuery(String query, DBUtil dbUtil)
And then I could loop over the rows of the ResultSet
and populate the relevant DataStructure
for each row. The problem is that I would still have to close the returned ResultSet
and closing ResultSet
in a different method seems like bad design.
I guess what I'm looking for is maybe something similar to Python's concept of function decorators so that I could "decorate" a JDBC query to take care of most of the boilerplate present in sampleJDBCQuery
above. How could I achieve this?