【转载&原创】python导出mysql数据字典到docx

转载自 https://blog.csdn.net/sunyuhua_keyboard/article/details/80595136

import pymysql
from docx import Document
connection=pymysql.connect(host='XXXXXX',
                           user='XXXX',
                           password='XXXX',
                           db='information_schema',
                           port=3306,
                           charset='utf8')#information_schema 这个不能变,其他是你的数据库的连接信息
schema='XXXXX' #要导出的数据库的名字
cursor=connection.cursor()
sql="select table_name,table_comment from information_schema.tables where TABLE_SCHEMA = '"+str(schema)+"'"
cursor.execute(sql)
tableInfoList=cursor.fetchall()
doc=Document()
for tableInfo in tableInfoList:
    tableName=tableInfo[0]
    tableComment=tableInfo[1]
    table_explain = tableName+",注解:"+tableComment+",对应数据库的表:"
    tableInfoSql="SELECT C.COLUMN_NAME AS '字段名',C.COLUMN_TYPE AS '数据类型',C.IS_NULLABLE AS '允许为空',C.EXTRA AS 'PK',C.COLUMN_COMMENT AS '字段说明' FROM information_schema.COLUMNS C INNER JOIN TABLES T ON C.TABLE_SCHEMA = T.TABLE_SCHEMA AND C.TABLE_NAME = T.TABLE_NAME WHERE T.TABLE_SCHEMA = '"+str(schema)+"' and T.TABLE_NAME='"+str(tableName)+"'"
    cursor.execute(tableInfoSql)
    tableColumnInfoList = cursor.fetchall()
    p = doc.add_paragraph('')
    p.add_run(table_explain, style="Heading 1 Char")
    row=cursor.rowcount
    table=doc.add_table(rows=1,cols=5)
    table.style = 'TableGrid'
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text='字段名'
    hdr_cells[1].text = '字段类型'
    hdr_cells[2].text = '允许为空'
    hdr_cells[3].text = 'PK'
    hdr_cells[4].text = '字段说明'
    for tableColumn in tableColumnInfoList:
        new_cells = table.add_row().cells
        new_cells[0].text=tableColumn[0]
        new_cells[1].text = tableColumn[1]
        new_cells[2].text = tableColumn[2]
        new_cells[3].text = tableColumn[3]
        new_cells[4].text = tableColumn[4]
    p = doc.add_paragraph('')
doc.save('D:/paoyou.docx')

补充一下我的环境安装,需要先安装几个依赖库:

# mysql依赖库
pip install pymysql

# docx操作库
pip install python-docx

建议使用国内的pip镜像库:

# 临时使用
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple some-package

# 设为默认
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

# 摘自清华镜像站
# https://mirror.tuna.tsinghua.edu.cn/help/pypi/

 

你可能感兴趣的:(python)