Efficient way to Handle ResultSet in Java(在 Java 中处理 ResultSet 的有效方法)
问题描述
我在 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?
这是我尝试过的:
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 和 DB 连接
完成
既然您已经发布了代码,我已经对其进行了一些更改.
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 的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Java 中处理 ResultSet 的有效方法


基础教程推荐
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01