之前写代码模版生成工具的时候,想要根据表结构直接生成相关代码,需要获取表字段和相关信息,走过一些弯路,特此记录。
本文对应mysql版本:mysql 5.6
show create table
show create table 表名称
这也是我每次下意识想到的语句。语义好记,可以直接查看建表语句,但不便于代码处理。
information_schema.COLUMNS
select * from information_schema.COLUMNS where TABLE_SCHEMA = '库名称' and TABLE_NAME = '表名称'
相对show create table
而言,相对简单,信息全面,可以查询出来字段的名称、类型、键、权限、注释和其他信息。为了获取字段名称,故我脚本中使用这个作为获取表结构的方法。
desc
desc 表名称
简单易用,可以获取到 COLUMNS 中的比较重要的字段:名称、类型、是否为空、键、默认值、额外信息。但无法获取字段的注释。
附:information_schema.COLUMNS字段和含义
字段名称 | 含义 |
---|---|
TABLE_CATALOG | 表类型(没搞懂干啥用) |
TABLE_SCHEMA | 所属库名称 |
TABLE_NAME | 表名称 |
COLUMN_NAME | 字段名称 |
ORDINAL_POSITION | 位置序号 |
COLUMN_DEFAULT | 默认值 |
IS_NULLABLE | 是否可为空 |
DATA_TYPE | 数据类型 |
CHARACTER_MAXIMUM_LENGTH | 字符串最大长度 (数值类型为空) |
CHARACTER_OCTET_LENGTH | 字符串最大存储长度 (一般与上一字段相同) |
NUMERIC_PRECISION | 数值精度 (非数值类型为空) |
NUMERIC_SCALE | 数值小数位数 (非数值类型为空) |
DATETIME_PRECISION | 日期精度 |
CHARACTER_SET_NAME | 编码方式 |
COLLATION_NAME | 排序方式 |
COLUMN_TYPE | 字段类型 |
COLUMN_KEY | 字段涉及的key (主键、唯一键等) |
EXTRA | 其他(如 auto_increment) |
PRIVILEGES | 权限 |
COLUMN_COMMENT | 字段注释 |
GENERATION_EXPRESSION | 代表达式 (这个没搞懂,mysql可以表继承?) |