Mysql技术之“如何用Java代码获取数据库的表信息的工具类(所有表的信息和指定表的信息)”

一.如何获取数据库的表信息的工具类

Mysql技术之“如何用Java代码获取数据库的表信息的工具类(所有表的信息和指定表的信息)”

二.代码

import org.springframework.util.StopWatch;
import java.sql.*;

public class DatabaseMetadataExample {

    // 数据库连接配置
    private static final String URL = "jdbc:mysql://localhost:3306/your_DataName?useInformationSchema=true";
    private static final String USER = "your_username";
    private static final String PASSWORD = "your_password";

    /**
     * 获取数据库的:表名、表备注、字段、字段类型、字段备注
     *
     * 例如:
     *
     * 表结构
     * CREATE TABLE `t_user` (
     *   `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
     *   `user_name` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '用户名称',
     *   `user_age` int(10) NOT NULL DEFAULT '0' COMMENT '用户年龄'
     *   PRIMARY KEY (`id`) USING BTREE
     * ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户表';
     *
     * 结果值
     * 表名: t_user, 备注:用户表
     *   === 字段信息 ===
     *   字段: id, 类型: BIGINT, 备注:
     *   字段: user_name, 类型: String, 备注: 用户名称
     *   字段: user_age, 类型: INT, 备注: 用户年龄
     *
     * @param args
     */
    public static void main(String[] args) {
        // 计时器
        StopWatch stopWatch = new StopWatch();
        // 开始计时:转运单号 +  "获取轨迹任务执时间"
        stopWatch.start("获取数据库表信息");
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {
            // 根据t_user表名获取表的信息
//            getTableDetails(conn, "t_user");

            DatabaseMetaData metaData = conn.getMetaData();
            // 1. 获取所有表信息
            System.out.println("=== 表信息 ===");
            // %号表示所有的表
            ResultSet tables = metaData.getTables(null, null, "%", new String[]{"TABLE"});
            while (tables.next()) {
                String tableName = tables.getString("TABLE_NAME");
                String tableComment = tables.getString("REMARKS");
                System.out.println("表名: " + tableName + ", 备注: " + tableComment);

                // 2. 获取表的字段信息
                System.out.println("  === 字段信息 ===");
                ResultSet columns = metaData.getColumns(null, null, tableName, "%");
                while (columns.next()) {
                    String columnName = columns.getString("COLUMN_NAME");
                    String columnComment = columns.getString("REMARKS");
                    String columnType = columns.getString("TYPE_NAME");
                    System.out.println("  字段: " + columnName +
                            ", 类型: " + columnType +
                            ", 备注: " + columnComment);
                }
                columns.close();
            }
            tables.close();

        } catch (SQLException e) {
            System.out.println("e = " + e);
        }
        stopWatch.stop();
        System.out.println(stopWatch.getLastTaskName() + ": 执行的时间:" + stopWatch.getTotalTimeSeconds());
    }

    /**
     * 根据表名获取表的信息
     *
     * @param conn 数据库链接对象
     * @param tableName 指定的表名:t_user
     * @throws SQLException
     */
    public static void getTableDetails(Connection conn, String tableName) throws SQLException {
        DatabaseMetaData metaData = conn.getMetaData();

        // 获取表信息
        ResultSet tables = metaData.getTables(null, null, tableName, new String[]{"TABLE"});
        if (tables.next()) {
            String tableComment = tables.getString("REMARKS");
            System.out.println("表: " + tableName + ", 备注: " + tableComment);
        }
        tables.close();

        // 获取字段信息
        System.out.println("字段列表:");
        ResultSet columns = metaData.getColumns(null, null, tableName, "%");
        while (columns.next()) {
            String columnName = columns.getString("COLUMN_NAME");
            String columnComment = columns.getString("REMARKS");
            String columnType = columns.getString("TYPE_NAME");
            int columnSize = columns.getInt("COLUMN_SIZE");

            System.out.println(String.format("  %-20s %-15s %-10s %s",
                    columnName, columnType + "(" + columnSize + ")",
                    columns.getString("IS_NULLABLE"), columnComment));
        }
        columns.close();

        // 获取主键信息
        System.out.println("主键:");
        ResultSet primaryKeys = metaData.getPrimaryKeys(null, null, tableName);
        while (primaryKeys.next()) {
            System.out.println("  " + primaryKeys.getString("COLUMN_NAME"));
        }
        primaryKeys.close();
    }
}

 

三.效果

表结构

CREATE TABLE `t_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`user_name` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '用户名称',
`user_age` int(10) NOT NULL DEFAULT '0' COMMENT '用户年龄'
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户表';


结果值

表名: t_user, 备注:用户表
=== 字段信息 ===
字段: id, 类型: BIGINT, 备注:
字段: user_name, 类型: String, 备注: 用户名称
字段: user_age, 类型: INT, 备注: 用户年龄

 

posted @ 2026-02-11 10:21  骚哥  阅读(26)  评论(0)    收藏  举报