I have about 40 web services and for each, I have the following code to get the results from the database. At most, I only retrieve about 200 rows from the database, many times way less than that. However, I was told by a fellow developer that this code is not very efficient, especially the getColumnName
method, which is expensive. I just thought I'd use getColumnName
as a key because it's descriptive. Is there a more efficient way of doing the same thing as below? If so, how can I make this more efficient? Any design patterns I should look into to make this better? Thanks in advance.
try{
...
//Open Db Connection
...
ResultSet rs = stmt.executeQuery(QueryClass.getQuery());
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
while(rs.next()){
HashMap<String, Object> map = new HashMap<String, Object>(columnCount);
for (int i = 1; i <= columnCount; i++ ) {
map.put(rsmd.getColumnName(i), rsmd.getObject(i));
}
//add to arraylist
list.add(map);
}
} catch(SQLException e){
.....
}
If you are not seeing a performance issue then there's really no need to change your code for efficiency reasons alone. If the structure you are using makes sense to you then you should stick with it.
There are a few other options you might want to consider:
Have a separate list of column names that you store once:
List<String> columnNames;
List<List<Object>> rowData;
Record the data by column rather than by row:
Map<String, List<Object>> columnData;
Encapsulate the queries by defining an interface that can be implemented using a method appropriate to the table, allowing you to change the implementation if you have a performance issue without changing the interface.
For example:
public interface Table {
List<String> getColumnNames();
Object getValue(String column, int row);
}