package com.itjob.jdbc;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.NamingException;

public class DataBaseMetaDataTest {
	public static void main(String[] args) {
		Connection con = null;
		String jndiname = "jdbcPool/mydatasource";
		try {
			con = DBCon.getConnectionFromPooledDataSource(jndiname);
			// 测试数据库信息
			DatabaseMetaData dm = con.getMetaData();
			System.out.println("1. 数据库的基本信息");
			System.out.println("Database is " + dm.getDatabaseProductName());
			System.out.println("Database version is "
					+ dm.getDatabaseProductVersion());
			System.out.println("JDBC Driver is " + dm.getDriverName());
			System.out.println("JDBC driver version is "
					+ dm.getDriverVersion());
			// 获取数据库中目录(数据库)的信息
			System.out.println("2. 数据库中目录(数据库)的信息");
			ResultSet catalogs = dm.getCatalogs();
			while (catalogs.next()) {
				System.out.println(catalogs.getString(1));
			}
			// 获取数据库中模式的信息
			System.out.println("3. 数据库中模式的信息");
			ResultSet schemas = dm.getSchemas();
			while (schemas.next()) {
				System.out.println(schemas.getString(1));
			}
			// 获取数据库中各个表的情况
			System.out.println("4. 数据库中各个表的信息");
			ResultSet tables = dm.getTables("pubs", null, null, null);
			while (tables.next()) {
				for (int i = 0; i < 5; i++) {
					System.out.print(tables.getString(i + 1));
					System.out.print("  |  ");
				}
				System.out.println();
			}
			// 获取数据库表中各个列的信息
			System.out.println("5. 数据库表中各个列的信息");
			ResultSet columns = dm.getColumns(null, null, "student", null);
			while (columns.next()) {
				for (int i = 0; i < 18; i++) {
					System.out.print(columns.getString(i + 1));
					System.out.print("  |  ");
				}
				System.out.println();
			}
		} catch (NamingException ex) {
			System.err.println("Name Not Bound : " + ex.getMessage());
		} catch (SQLException ex) {
			System.err.println("SQLException : " + ex.getMessage());
		} finally {
			try {
				if (con != null)
					con.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		System.out.println("程序结束!!!");
	}
}
