python 导出mysql 视图_用Python生成MySql数据字典

项目的数据库字典表是一个很重要的文档。通过此文档可以清晰的了解数据表结构及开发者的设计意图。

通常为了方便我都是直接在数据库中建表,然后通过工具导出数据字典。

在Mysql数据库中有一个information_schema库,它提供了访问数据库元数据的方式。

什么是元数据呢?就是关于数据的数据,如数据库名、表名、列的数据类型、访问权限等。

SCHEMATA表:提供了当前mysql实例中所有数据库的信息。是show databases的结果取之此表。

TABLES表:提供了关于数据库中的表的信息(包括视图)。详细表述了某个表属于哪个schema,表类型,表引擎,创建时间等信息。

show tables from schemaname的结果取之此表。

COLUMNS表:提供了表中的列信息。详细表述了某张表的所有列以及每个列的信息.

show columns from schemaname.tablename的结果取之此表。

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

#!/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生成数据库关系图。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值