sql查询数据封装到List中

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 getListMapBySql(String sql, Connection conn) {
		// 封装数据用
		List list = new ArrayList();// 声明返回的对象
		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 mm = new HashMap(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) {
			}
		}

	}
}

你可能感兴趣的:(数据库)