zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

jdbc获取数据库表结构

2023-03-07 09:11:47 时间
 public void getTables(Connection con, String catalog, String schemaPattern, String tableNamePattern) throws SQLException {
 	// 获取数据库元数据
    DatabaseMetaData metaData = con.getMetaData();
    // 查询表元数据,pattern可使用通配符查询(%,?)
    ResultSet tableRet = metaData.getTables(
            catalog,
            schemaPattern,
            tableNamePattern,
            new String[]{"TABLE","VIEW"}
    );
    // 遍历表
    while (tableRet.next()) {
        String tableName = tableRet.getString("TABLE_NAME");
        System.out.println("======" + tableName + "======");
        // 查找表字段元数据
        ResultSet colRet = metaData.getColumns(
                catalog,
                schemaPattern,
                tableName,
                "%"
        );
        // 遍历表字段
        while (colRet.next()) {
        	// 字段名
            String columnName = colRet.getString("COLUMN_NAME");
            // 字段类型
            String typeName = colRet.getString("TYPE_NAME");
            // 字段大小
            Integer columnSize = colRet.getInt("COLUMN_SIZE");
            // 数字类型精度值
            Integer decimalDigits = colRet.getInt("DECIMAL_DIGITS");
            // 可为空值
            Boolean nullable = colRet.getBoolean("NULLABLE");
            System.out.println(
                    columnName
                            + ":"
                            + typeName
                            + "(" + columnSize + "," + decimalDigits + ")"
                            + (nullable ? " nullable" : "")
            );
        }
    }
}

注:不同数据库对catalog,schema有不同的实现

数据库

catalog

schema

mysql

库名

不支持(null)

oracle

不支持()

用户名

mssql

库名

owner

输出样例:

t_log id:BIGINT(19,0) content:VARCHAR(128,0) nullable log_created:DATETIME(26,0) log_modified:DATETIME(26,0)