Reputation: 3318
Well, that must be an easy one but I can't find the solution anywhere. And I am still not enough comfortable using Java to figure out the way to do it.
So far, I am able to loop through a ResultSet
and I'm quite proud of myself already.
I would like a List so I could simply loop through it and then call something like myRow.get('ColumnName');
.
Also, there MIGHT another data type instead of a Hashtable
to store the key/value. Any tips?
Thank you very much!
Upvotes: 2
Views: 3883
Reputation: 51
what I understand it would be something like this:
LinkedList<HashTable<String,String>> list = new LinkedList<>();
while(rs.next()){
Hashtable<String, String> currentRowMap = new Hashtable<>();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
// retrieves column name and value.
String key = rsmd.getColumnLabel(i);
String value = rs.getString(rsmd.getColumnName(i));
if (value == null) {
value = "null";
}
// builds map.
currentRowMap .put(key, value);
}
list.add(currentRowMap);
}
return list;
Upvotes: 0
Reputation: 28752
myRow.get('ColumnName');
is already in ResultSet
, see getObject(String columnLabel). Now, one difference between ResultSet
and Map
is that a ResultSet
is not (always) random access. Once you go past a row, using ResultSet.next()
, it may not allow you to "rewind" to the previous row. There is good reason for this: the number of elements in ReusltSet can be arbitrarily large and the memory requirement on a list of map would be prohibitive.
If you do decide to convert it to a List<Map<String, Object>>
then you should create your own implementation of both the List
and the Map
, such that a Map<String /*columnName*/, Integer /*Index*/>
is gives the index of a column-name in each array. I am speaking from experience, I had to change an implementation where a iterating through list of column names was too expensive.
Upvotes: 4
Reputation: 4324
I would use HashMap
. Hashtable
is old school...
Example:
HashMap<String, Object> p = new HashMap<String, Object>();
p.put("ResultSetkey1","ResultSetvalue1");
p.put("ResultSetkey2","ResultSetvalue2");
Upvotes: 1