項目的數據庫字典表是一個很重要的文檔。通過此文檔可以清晰的了解數據表結構及開發者的設計意圖。
通常為了方便我都是直接在數據庫中建表,然后通過工具導出數據字典,但是通過一番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生成數據庫關系圖