-1

有没有办法将 ResultSet 中包含的表的每一行存储到 HashMap 中(使每一行成为 HashMap 的条目)。

4

2 回答 2

4

从您的结果集中获取一列(被认为是主键),并将其用于 Map 的 key 属性。您可以创建自定义类,将其余列作为其字段(简单 POJO),并将其用于 value 属性。一个例子:

public class MyRow {
    private String col1;
    private int col2;
    ...
    // the constructor
    public MyRow(String s, int i, ...) {
        this.col1 = s;
        this.col2 = i;
        ...
    }
}

假设您将结果集中的 int 列(如果存在)作为映射的键,您将拥有如下所示的内容:

Map<Integer, MyRow> map = new HashMap<Integer, MyRow>(0);
ResultSet rs;
// get your result set from some db query or whatever
while(rs.next()) {
    MyRow mr = new MyRow(rs.getString(yourCol1Index), rs.getInt(yourCol2Index), ...);
    map.put(rs.getInt(yourKeyColumnIndex), mr);
}
// finaly release the resources
rs.close();
于 2012-10-05T12:31:13.600 回答
3

你能做到吗?是的。您编写一个自定义类来表示一行的数据内容,然后读取这些行,为每一行创建一个实例,并使用适当的键将其放入 HashMap 中。

有没有更简单或更好的方法?不是我知道的。

于 2012-10-05T12:25:02.087 回答