sql查询数据封装到List<map>中

package test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SqlToListMap {
	public static List<Map> getListMapBySql(String sql, Connection conn) {
		// 封装数据用
		List<Map> list = new ArrayList<Map>();// 声明返回的对象
		PreparedStatement pstm = null;
		ResultSet rs = null;
		// Connection con = null;
		try {
			// con = ds.getConnection();
			// 执行查询
			pstm = conn.prepareStatement(sql);
			rs = pstm.executeQuery();
			// 分析结果集
			ResultSetMetaData rsmd = rs.getMetaData();
			// 获取列数
			int cols = rsmd.getColumnCount();
			// 遍历数据
			while (rs.next()) {
				// 一行数据
				Map<String, String> mm = new HashMap<String, String>(4);
				// 遍历列
				for (int i = 0; i < cols; i++) {
					// 获取列名
					String colName = rsmd.getColumnLabel(i + 1);
					// BeanCtx.out("colName="+colName);
					// 获取数据
					String fdValue = rs.getString(i + 1);

					// String fdValue = rs.getString(fdName);
					mm.put(colName, fdValue);
				}

				// 将这个map放到list
				list.add(mm);

			}
		} catch (Exception e) {
			throw new RuntimeException(e);

		} finally {
			close(conn, pstm, rs);// 释放资源
		}
		return list;
	}

	public static void close(Connection conn, Statement stat, ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException ex) {
			}
		}

		if (stat != null) {
			try {
				stat.close();
			} catch (SQLException ex) {
			}
		}

		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException ex) {
			}
		}

	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值