用Python生成MySql數據字典

項目的數據庫字典表是一個很重要的文檔。經過此文檔能夠清晰的瞭解數據表結構及開發者的設計意圖。
一般爲了方便我都是直接在數據庫中建表,而後經過工具導出數據字典。python

在Mysql數據庫中有一個information_schema庫,它提供了訪問數據庫元數據的方式。
什麼是元數據呢?就是關於數據的數據,如數據庫名、表名、列的數據類型、訪問權限等。
SCHEMATA表:提供了當前mysql實例中全部數據庫的信息。是show databases的結果取之此表。
TABLES表:提供了關於數據庫中的表的信息(包括視圖)。詳細表述了某個表屬於哪一個schema,表類型,表引擎,建立時間等信息。
show tables from schemaname的結果取之此表。
COLUMNS表:提供了表中的列信息。詳細表述了某張表的全部列以及每一個列的信息.
show columns from schemaname.tablename的結果取之此表。mysql

瞭解了生成數據字典的原理後看一下實現代碼:sql

#!/usr/bin/env python
# -*- coding: utf-8 -*- 

import mysql.connector as mysql
import sys
import getopt
reload(sys)
sys.setdefaultencoding('utf8')


def usage():
    print 'help:'
    print '--host db server,default localhost'
    print '--port db port,default 3306'
    print '--user db username,default root'
    print '--password db password,default blank'
    print '--database db name'
    print '--output markdown output file,default current path'

if __name__ == '__main__':
    try:
        opts,args = getopt.getopt(sys.argv[1:],"h",["help","host=","port=","database=","user=","password=","output="])
    except getopt.GetoptError:
        sys.exit()
    if 'help' in args:
        usage()
        sys.exit()
        print opts
    host = 'localhost'
    user = 'root'
    password = ''
    database = ''
    port = 3306
    output = './markdown.out'

    for op,value in opts:
        if op == '--host':
            host = value
        elif op == '--port':
            port = value
        elif op == '--database':
            database = value
        elif op == '--user':
            user = value
        elif op == '--password':
            password = value
        elif op == '--output':
            output = value
        elif op == '-h':
            usage()
            sys.exit()
        if database == '':
            usage()
        #    sys.exit()
    conn = mysql.connect(host=host,port=port,user=user,password=password,database='information_schema')
    cursor = conn.cursor()
    cursor.execute("select table_name,table_comment from information_schema.tables where table_schema='%s' and table_type='base table'" % database)
    tables = cursor.fetchall()
    
    markdown_table_header = """### %s (%s) 
    字段名 | 字段類型 | 默認值 | 註解
    ---- | ---- | ---- | ---- 
    """
    markdown_table_row = """%s | %s | %s | %s
    """
    f = open(output,'w')
    for table in tables:
        cursor.execute("select COLUMN_NAME,COLUMN_TYPE,COLUMN_DEFAULT,COLUMN_COMMENT from information_schema.COLUMNS where table_schema='%s' and table_name='%s'"% (database,table[0]))
        tmp_table = cursor.fetchall()
        p = markdown_table_header % table;
        for col in tmp_table:
            p += markdown_table_row % col
        f.writelines(p)
        f.writelines('\r\n')
    f.close()
    print 'generate markdown success!'

上面的執行結果會輸出 markdown 格式的文件。數據庫

數據庫表名

字段名 字段類型 默認值 註解

後面會寫一篇用Python生成數據庫關係圖。markdown

相關文章
相關標籤/搜索