java中的resultset,在Java中处理ResultSet的有效方法

本文探讨了在Java中使用ResultSet时如何高效地转换为HashMap,并讨论了关闭ResultSet的最佳实践。作者提供了将ResultSet转换为HashMap的方法,以及使用ArrayList替代的改进版本,同时寻求更优的处理方式和代码实现建议。
摘要由CSDN通过智能技术生成

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.

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;

}

解决方案

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

Done

EDIT: 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;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值