使用Python生成MySql数据字典

2017-03-28  本文已影响0人  老__鹰

项目的数据库字典表是一个很重要的文档。通过此文档可以清晰的了解数据表结构及开发者的设计意图。
通常为了方便我都是直接在数据库中建表,然后通过工具导出数据字典,但是通过一番Google后发现导出数据字典的工具很多,但是没有找到一个(如果有请告诉我啊)可以连带字段注释都导出的工具。好吧!自己造轮子。

在Mysql数据库中有一个information_schema库,它提供了访问数据库元数据的方式。什么是元数据呢?就是关于数据的数据,如数据库名、表名、列的数据类型、访问权限等。
SCHEMATA表:提供了当前mysql实例中所有数据库的信息。是show databases的结果取之此表。
TABLES表:提供了关于数据库中的表的信息(包括视图)。详细表述了某个表属于哪个schema,表类型,表引擎,创建时间等信息。是show tables from schemaname的结果取之此表。
COLUMNS表:提供了表中的列信息。详细表述了某张表的所有列以及每个列的信息。是show columns from schemaname.tablename的结果取之此表。

了解了生成数据字典的原理后看一下实现代码:

# -*- coding: utf-8 -*- 

import mysql.connector as mysql
import sys
reload(sys)
#考虑注释是中文
sys.setdefaultencoding('utf8')

conn = mysql.connect(host='192.168.1.210',user='root',password='',database='information_schema')
cursor = conn.cursor()
cursor.execute("select table_name from information_schema.tables where table_schema='数据库名' and table_type='base table'")
tables = cursor.fetchall()

markdown_table_header = """### %s 
字段名 | 字段类型 | 默认值 | 注解
---- | ---- | ---- | ---- 
"""
markdown_table_row = """%s | %s | %s | %s
"""
#保存输出结果
f = open('markdown.out','w')
for table in tables:
    cursor.execute("select COLUMN_NAME,COLUMN_TYPE,COLUMN_DEFAULT,COLUMN_COMMENT from information_schema.COLUMNS where table_schema='数据库名' and table_name='%s'"% table)
    tmp_table = cursor.fetchall()
    p = markdown_table_header % table;
    for col in tmp_table:
        p += markdown_table_row % col
    #print p
    f.writelines(p)
f.close()

上面的执行结果会输出 markdown 格式的表

数据库表名

字段名 字段类型 默认值 注解

后面会写一篇用Python生成数据库关系图

上一篇下一篇

猜你喜欢

热点阅读