简体   繁体   English

如何在Hashtable列表中转换ResultSet?

[英]How do I convert a ResultSet in a List of Hashtable?

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. 而且我仍然不太愿意使用Java来找到实现它的方法。

So far, I am able to loop through a ResultSet and I'm quite proud of myself already. 到目前为止,我已经能够遍历ResultSet并且我已经为自己感到骄傲。

I would like a List so I could simply loop through it and then call something like myRow.get('ColumnName'); 我想要一个列表,这样我就可以循环遍历它,然后调用诸如myRow.get('ColumnName');类的东西myRow.get('ColumnName'); .

Also, there MIGHT another data type instead of a Hashtable to store the key/value. 另外,可能还有其他数据类型而不是Hashtable来存储键/值。 Any tips? 有小费吗?

Thank you very much! 非常感谢你!

myRow.get('ColumnName'); is already in ResultSet , see getObject(String columnLabel) . 已经在ResultSet ,请参见getObject(String columnLabel) Now, one difference between ResultSet and Map is that a ResultSet is not (always) random access . 现在, ResultSetMap之间的区别是ResultSet不是(总是) 随机访问 Once you go past a row, using ResultSet.next() , it may not allow you to "rewind" to the previous row. 使用ResultSet.next()一行后,它可能不允许您“倒回”到上一行。 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. 这样做有充分的理由:ReusltSet中的元素数可以任意大,并且map列表上的内存需求将是令人望而却步的。

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. 如果确实决定将其转换为List<Map<String, Object>> ,则应创建自己的ListMap ,以使Map<String /*columnName*/, Integer /*Index*/>是给出每个数组中列名的索引。 I am speaking from experience, I had to change an implementation where a iterating through list of column names was too expensive. 从经验来看,我不得不更改一个实现,其中遍历列名列表过于昂贵。

I would use HashMap . 我会使用HashMap Hashtable is old school... Hashtable是老派...

Example: 例:

HashMap<String, Object> p = new HashMap<String, Object>();
p.put("ResultSetkey1","ResultSetvalue1");
p.put("ResultSetkey2","ResultSetvalue2");

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM