在Java中处理ResultSet的有效方法 [英] Efficient way to Handle ResultSet in Java
问题描述
我在Java中使用ResultSet,并不确定如何正确关闭它。我正在考虑使用ResultSet构造一个HashMap,然后关闭ResultSet。这种HashMap技术是否有效,还是有更有效的方法来处理这种情况?我需要键和值,所以使用HashMap看起来像是一个合理的选择。
I'm using a ResultSet in Java, and am not sure how to properly close it. I'm considering using the ResultSet to construct a HashMap and then closing the ResultSet after that. Is this HashMap technique efficient, or are there more efficient ways of handling this situation? I need both keys and values, so using a HashMap seemed like a logical choice.
如果使用HashMap是最有效的方法,那么如何构造和使用HashMap在我的代码中?
If using a HashMap is the most efficient method, how do I construct and use the HashMap in my code?
以下是我试过的:
Here's what I've tried:
public HashMap resultSetToHashMap(ResultSet rs) throws SQLException {
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
HashMap row = new HashMap();
while (rs.next()) {
for (int i = 1; i <= columns; i++) {
row.put(md.getColumnName(i), rs.getObject(i));
}
}
return row;
}
推荐答案
- 遍历ResultSet
- 为每行创建一个新对象,以存储您需要的字段
- 将此新对象添加到ArrayList或Hashmap或无论你喜欢什么
- 关闭ResultSet,Statement和数据库连接
- Iterate over the ResultSet
- Create a new Object for each row, to store the fields you need
- Add this new object to ArrayList or Hashmap or whatever you fancy
- Close the ResultSet, Statement and the DB connection
完成
编辑:现在您已经发布了代码,我已对其进行了一些更改。
now that you have posted code, I have made a few changes to it.
public List resultSetToArrayList(ResultSet rs) throws SQLException{
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
ArrayList list = new ArrayList(50);
while (rs.next()){
HashMap row = new HashMap(columns);
for(int i=1; i<=columns; ++i){
row.put(md.getColumnName(i),rs.getObject(i));
}
list.add(row);
}
return list;
}
这篇关于在Java中处理ResultSet的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!