JDBC之ResultSetMetaData

1、ResultSetMetaData meta = rs.getMetaData();
2、通过ResultSetMetaData可以获得结果有几列、各列名、各列别名、各列类型等。 

3、可以将ResultSet放入Map(key:列名 value:列值)。

具体代码如下:

package cn.itcast.jdbc;

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

import org.junit.Test;

/**
 * 测试结果集元信息
 */
public class ResultSetMetaDataTest {
	
	/**
	 * 测试从数据库中读取数据
	 * @throws SQLException
	 */
	@Test
	public void testRead() throws SQLException {
		List> datas = 
				read("select id, name as n, birthday from user where id < 5");
		System.out.println(datas);
	}
	
	/**
	 * 获取数据
	 * @param sql
	 * @return
	 * @throws SQLException
	 */
	static List> 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();
			ResultSetMetaData rsmd = rs.getMetaData();
			int count = rsmd.getColumnCount();//返回结果集中的列数
			String[] colNames = new String[count];
			for(int i = 1; i <= count; i ++) {
				//这里可以正确打印出MySQL的数据类型
				System.out.print(rsmd.getColumnClassName(i) + "\t");
				System.out.print(rsmd.getColumnType(i) + "\t");
				System.out.print(rsmd.getColumnTypeName(i) + "\t");
				//获取列名
				System.out.print(rsmd.getColumnName(i) + "\t");
				//获取列的别名
				System.out.println(rsmd.getColumnLabel(i));
				//将查询的列的别名封装进数组中
				colNames[i - 1] = rsmd.getColumnLabel(i);
			}
			List> datas = new ArrayList>();
			
			while(rs.next()) {
				//用于存储每一行的数据
				Map data = new HashMap();
				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);
		}
		
	}
	
}
测试结果:

java.lang.Integer 4 INT id id
java.lang.String 12 VARCHAR name n
java.sql.Date 91 DATE birthday birthday
[{birthday=2017-06-30, id=1, n=zhangsan}, {birthday=2017-06-06, id=2, n=lisi}, {birthday=2017-05-30, id=3, n=wangwu}, {birthday=1987-01-01, id=4, n=name1}]




你可能感兴趣的:(JDBC,jdbc)