I'm making a wrapper for querying the database so that I can more easily control the flow of database management and to make it easier for me to write data beans around my database. This code is going to be used a ton so I'm looking to make it as clean as possible.
/**
* Query the database.
*
* @param sql
* The query statement
* @return List of rows returned by the query.
*/
public List<Map<String, Object>> query(String sql) {
return this.query(sql, null);
}
/**
* Query the database.
*
* @param sql
* The query statement
* @param params
* The prepared statement parameters (in order).
* @return List of rows returned by the query.
*/
public List<Map<String, Object>> query(String sql, Object[] params) {
final String METHODNAME = "query";
List<Map<String, Object>> resList = null;
try {
if (conn != null && !conn.isClosed()) {
resList = new ArrayList<Map<String, Object>>();
PreparedStatement stmt = conn.prepareStatement(sql);
if (params != null && params.length > 0) {
for (int i = 1; i <= params.length; i++) { // 1 based, not 0
stmt.setObject(i, params[i - 1]);
}
}
ResultSet res = stmt.executeQuery();
while (res.next()) {
Map<String, Object> row = new HashMap<String, Object>();
for (int i = 1; i <= res.getMetaData().getColumnCount(); i++) {
String key = res.getMetaData().getColumnName(i);
Object val = res.getObject(i);
row.put(key, val);
resList.add(row);
}
}
} else {
logger.log(LogLevel.ALL, CLASSNAME, METHODNAME, "Attempted to run query when "
+ "there was no established connection to the database.");
}
} catch (Throwable e) {
logger.log(LogLevel.ERROR, CLASSNAME, METHODNAME,
"An error occurred when trying to run the query.");
}
return resList;
}