python自动将数据库表结构转换成markdown文档

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/chenyun19890626/article/details/54977120

背景

需要一份数据库表的字典,方便查看,而表有100多张,手动写就太悲剧了,于是我写了一段脚本将所有表自动转换成一个mardown文档

效果图

这里写图片描述

代码

#coding:utf-8
import os
import re
output_path="D:\Bolo_Table_Dictionary.md"
output_obj = open(output_path, 'a')
output_obj.write("[TOC]")
output_obj.write("\n")
try:
    for parent,dirs,files in os.walk("D:\sql") :

        for file in files :
            file = os.path.join(parent, file)
            print file
            file_object = open(file)
            try:
                all_the_text = file_object.read()
                table=re.findall(r"CREATE TABLE `([^`]+)`",all_the_text)
                comment=re.findall(r"COMMENT='([^']+)'",all_the_text)
                if len(table)==0:
                    continue
                if len(comment)==0:
                    comment.append("")
                output_obj.write("######"+table[0]+" "+comment[0])
                output_obj.write("\n")
                output_obj.write("| 字段 | 类型 | 注解 |")
                output_obj.write("\n")
                output_obj.write("| ---- | ---- | ---- |")
                output_obj.write("\n")
                result=re.findall(r"CREATE TABLE `[^`]+` \(([\s\S]+)PRIMARY KEY",all_the_text)
                str = re.compile(r",|'|`|DEFAULT|NOT|NULL|AUTO_INCREMENT|COMMENT")
                linestr = str.sub("", result[0])
                lines=linestr.split('\n')
                for line in lines:
                    if len(line)>0 :
                        cols=line.split(" ")
                        vals = []
                        for col in cols:
                            if len(col)>0:
                                vals.append(col)
                        if len(vals)>0:
                            if len(vals)<3:
                                vals.append("")
                            try:
                                output_obj.writelines("| "+vals[0]+" | "+vals[1]+" | "+vals[2]+" |")
                                output_obj.write("\n")
                            except Exception,e:
                                print vals

            finally:
                file_object.close()
finally:
    output_obj.close()
展开阅读全文

没有更多推荐了,返回首页