gdjlc

培养良好的习惯,每天一点一滴的进步,终将会有收获。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

原理:读取系统表的数据,调用python-docx库生成word文档。

import pymysql
from docx import Document
from docx.shared import Inches


document = Document()
document.add_heading('数据库表结构', 0)

conn = pymysql.connect(host='192.168.1.17', user='root', passwd="password", db='db1')
cur = conn.cursor()
cur.execute('''SELECT
                    t.table_schema,
                    t.table_name,
                    t.column_name,
                    t.column_type,
                    t.is_nullable,
                    t.column_default,
                    t.column_comment     
                FROM
                    INFORMATION_SCHEMA.COLUMNS t 
                WHERE table_schema in('db1')
                ORDER BY table_schema,table_name''')
col_list = cur.fetchall()

db_tb_list = []
for table_schema,table_name,column_name,column_type, is_nullable,column_default,column_comment  in col_list: 
    result = [r for r in db_tb_list if r[0] == table_schema and r[1] == table_name]
    if(len(result) == 0):  
        db_tb_list.append((table_schema,table_name))

db_tmp = ''
for db,tb in db_tb_list:
    if (db_tmp != db):
        document.add_heading('数据库' + db, 1)
    db_tmp = db
    document.add_heading('' + db + '.' + tb, 5)
 
    this_table = [r for r in col_list if r[0] == db and r[1] == tb]
    #添加表格:
    # 表格样式参数style可选:
    # Normal Table
    # Table Grid
    # Light Shading、 Light Shading Accent 1 至 Light Shading Accent 6
    # Light List、Light List Accent 1 至 Light List Accent 6
    # Light Grid、Light Grid Accent 1 至 Light Grid Accent 6
    # 其它省略...  
    table = document.add_table(rows=1, cols=5, style='Light Grid')
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = ''
    hdr_cells[1].text = '类型'
    hdr_cells[2].text = ''
    hdr_cells[3].text = '默认'
    hdr_cells[4].text = '说明'
    for table_schema,table_name,column_name,column_type, is_nullable,column_default,column_comment  in this_table:
        row_cells = table.add_row().cells       
        row_cells[0].text = column_name
        row_cells[1].text = column_type
        row_cells[2].text = '' if is_nullable is 'YES' else ''
        row_cells[3].text = '' if column_default is None else column_default
        row_cells[4].text = column_comment

document.save('数据库表结构.docx')

cur.close()
conn.close()

 

posted on 2022-11-08 17:53  gdjlc  阅读(313)  评论(0编辑  收藏  举报