数据库表信息获取(例如表字段的名称与类型)

package internal;

import parser.Configuration;

import java.sql.*;
import java.util.*;

public class DbReader {
    Configuration configuration;

    public DbReader() {
    }

    public DbReader(Configuration configuration) {
        this.configuration = configuration;
    }

    public void read() throws Exception {
        String url = "jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8";
        String username = "root";
        String password = "root";
        Class.forName("com.mysql.jdbc.Driver");//项目pom中需要引入jdbc依赖
        Connection conn = DriverManager.getConnection(url, username, password);

        String tableName = "hello";
        DatabaseMetaData databaseMetaData = conn.getMetaData();
        ResultSet resultSet = databaseMetaData.getColumns(null, username, tableName, null);
        List> tableResult = new ArrayList<>();

        while (resultSet.next()) {
            Map columnMap = new HashMap();
            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
            //获取列数
            int colNum = resultSetMetaData.getColumnCount();
            //遍历列,获取列信息
            for (int i = 1; i <= colNum; i++) {
                // 列名
                String name = resultSetMetaData.getColumnLabel(i);
                // 列属性
                Object value = resultSet.getObject(i);
                // 加入属性
                columnMap.put(name, value);
            }
            tableResult.add(columnMap);
            printColumn(columnMap);
        }
    }

    private void printColumn(Map columnMap) {
        Object columnName = null;
        Object columnType = null;
        Object columnRemark = null;
        Object columnSize = null;
        Object columnIsNullable = null;
        for (Map.Entry entry : columnMap.entrySet()) {
            String key = (String) entry.getKey();
            if (key.equals("COLUMN_NAME")) {
                columnName = entry.getValue();
            }
            if (key.equals("TYPE_NAME")) {
                columnType = entry.getValue();
            }
            if (key.equals("REMARKS")) {
                columnRemark = entry.getValue();
            }
            if (key.equals("COLUMN_SIZE")) {
                columnSize = entry.getValue();
            }
            if (key.equals("IS_NULLABLE")) {
                columnIsNullable = entry.getValue();
            }
        }
        System.out.println("列名:" + columnName + " , 类型:" + columnType + " , 备注:" + columnRemark
                + " , 列大小:" + columnSize + " , 是否允许空:" + columnIsNullable);
    }

}

 

你可能感兴趣的:(mysql)