python导出数据库结构文档

创建如下word文档模板

创建python脚本修改数据库信息,运行脚本即可

import pymysql
from docx import Document

# 数据库连接配置
config = {
    'host': '数据库地址',
    'user': '账户',
    'password': '密码',
    'database': '数据库名',
    'charset': 'utf8mb4',
    'port': 端口
}

# 连接数据库
conn = pymysql.connect(**config)
cursor = conn.cursor(pymysql.cursors.DictCursor)

# 获取数据库所有表
cursor.execute("SHOW TABLES;")
tables = [list(row.values())[0] for row in cursor.fetchall()]

doc = Document()
doc.add_heading('数据库表结构文档', 0)

index = 1

for table_name in tables:
    # 获取表注释、引擎、编码
    cursor.execute(f"SHOW CREATE TABLE `{table_name}`;")
    create_sql = cursor.fetchone()['Create Table']

    # 提取注释
    comment_line = [line for line in create_sql.split('\n') if 'COMMENT=' in line]
    table_comment = comment_line[0].split('COMMENT=')[-1].strip("'") if comment_line else ''

    engine = 'InnoDB' if 'ENGINE=InnoDB' in create_sql else ''
    charset = 'utf8_bin' if 'CHARSET=utf8' in create_sql else ''

    doc.add_paragraph(f"\n{index}、表名:{table_name}")
    doc.add_paragraph(f"注释:{table_comment}")
    doc.add_paragraph(f"引擎:{engine}")
    doc.add_paragraph(f"编码:{charset}")
    doc.add_paragraph(f"类型:BASE TABLE")

    # 获取字段信息
    cursor.execute(f"SHOW FULL COLUMNS FROM `{table_name}`;")
    columns = cursor.fetchall()

    table = doc.add_table(rows=1, cols=8)
    table.style = 'Table Grid'
    headers = ["序号", "字段名称", "字段描述", "字段类型", "长度", "允许空", "默认值", "注释"]
    for i, h in enumerate(headers):
        table.rows[0].cells[i].text = h

    for idx, col in enumerate(columns, 1):
        row_cells = table.add_row().cells
        row_cells[0].text = str(idx)
        row_cells[1].text = col['Field']
        row_cells[2].text = col['Comment']
        row_cells[3].text = col['Type'].split('(')[0]
        row_cells[4].text = col['Type'].split('(')[1].rstrip(')') if '(' in col['Type'] else '-'
        row_cells[5].text = '否' if col['Null'] == 'NO' else '是'
        row_cells[6].text = str(col['Default']) if col['Default'] is not None else 'NULL'
        row_cells[7].text = col['Comment']
    index = index + 1
doc.save('数据库表结构.docx')
print("文档生成成功:数据库表结构.docx")

cursor.close()
conn.close()

 

版权声明:
作者:小凡
链接:https://ye-w.cn/2025/11/14/89.html
来源:小凡笔记-我的技术记录
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
< <上一篇
下一篇>>