java_jdbc_利用结果集元数据将查询结果封装为map_MetaData

package cn.itcast.batch;

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

import cn.itcast.JdbcUtils;

public class ResultSetMetaData {

	public static void main(String[] args) throws SQLException {
		// TODO Auto-generated method stub
		List<Map<String, Object>> list = read2("select username,password from t_user where id <5 ");
		System.out.println(list);
	}

	// 一行数据
	public static Map<String, Object> read(String sql) throws SQLException {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();

			java.sql.ResultSetMetaData rsmd = rs.getMetaData();

			int count = rsmd.getColumnCount();
			String[] colNames = new String[count];

			for (int i = 1; i <= count; i++) {
				// System.out.println(rsmd.getColumnClassName(i) + " "
				// + rsmd.getColumnName(i) + " " + rsmd.getColumnLabel(i));
				colNames[i - 1] = rsmd.getColumnName(i);

			}
			Map<String, Object> data = null;
			if (rs.next()) {
				data = new HashMap<String, Object>();
				for (int i = 0; i < colNames.length; i++) {
					data.put(colNames[i], rs.getObject(colNames[i]));
				}
			}
			return data;
		} finally {
			JdbcUtils.free(rs, ps, conn);
		}
	}

	// 多行行数据
	public static List<Map<String, Object>> read2(String sql)
			throws SQLException {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();

			java.sql.ResultSetMetaData rsmd = rs.getMetaData();

			int count = rsmd.getColumnCount();
			String[] colNames = new String[count];

			for (int i = 1; i <= count; i++) {
				// System.out.println(rsmd.getColumnClassName(i) + " "
				// + rsmd.getColumnName(i) + " " + rsmd.getColumnLabel(i));
				colNames[i - 1] = rsmd.getColumnName(i);

			}
			List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
			while (rs.next()) {
				Map<String, Object> data = new HashMap<String, Object>();
				for (int i = 0; i < colNames.length; i++) {
					data.put(colNames[i], rs.getObject(colNames[i]));
				}
				datas.add(data);
			}
			return datas;
		} finally {
			JdbcUtils.free(rs, ps, conn);
		}
	}
}


posted @ 2014-01-18 19:33  MrMrCash  阅读(564)  评论(0编辑  收藏  举报