package com.itjob.jdbc;
import java.sql.*;

/**
 * 第6章 JDBC编程
 * 考题：编写一个类，查询MySQL数据库中test库student表的信息，并通过ResultSetMetaData类打印student表的所有类名和类型信息
 * @author AmigoXie
 */
public class ResultSetMetaDataTest {
	public static void main(String[] args) {
		Statement stmt = null;
		ResultSet rs = null;
		Connection con = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url = " jdbc:mysql://localhost:3306/test";
			con = DriverManager.getConnection(url, "root", "root123");  
			stmt = con.createStatement();
			String querySQL1 = "select * from student";
			rs = stmt.executeQuery(querySQL1);

			// 提取结果集的元数据
			ResultSetMetaData rsmd = rs.getMetaData();
			int colCount = rsmd.getColumnCount();
			String[] columnNames = new String[colCount];
			int[] columnTypes = new int[colCount];

			for (int i = 0; i < colCount; i++) {
				columnNames[i] = rsmd.getColumnName(i + 1);
				columnTypes[i] = rsmd.getColumnType(i + 1);
			}
			
			for (int i = 0; i < colCount; i++) {
				System.out.println(columnNames[i] + " " + columnTypes[i]);
			}
		} catch (Exception ex) {
			System.err.println(ex.getMessage());
		} finally {
			try {
				if (con != null)
					con.close();
			} catch (Exception e) {

			}
		}
	}
}
