Is this good style of java data access code, or is it too much try finally ?
public List<Item> getItems() throws ItemException {
ArrayList<Item> items = new ArrayList<Item>();
try {
Connection con = ds.getConnection();
try {
PreparedStatement pStmt = con.prepareStatement("SELECT ....");
try {
ResultSet rs = pStmt.executeQuery();
try {
while (rs.next()) {
Item item = new Item();
item.setItemNo(rs.getString("item_id"));
// ...
items.add(item);
}
} finally {
rs.close();
}
} finally {
pStmt.close();
}
} finally {
con.close();
}
} catch (SQLException e) {
throw new ItemException(e);
}
return items;
}
Compare it to my code:
Here is what
close()looks like:[EDIT] You’ll need to copy this code for the other types.
I also moved all this into a helper class called
DBOpso I just have to overrideprocessRow(ResultSet row)to do the actual processing and I can omit all that boilerplate code. In Java 5, the constructor ofDBOpreads:I’m passing in the logger so I can show which instance is actually polling data.