龙空技术网

Mysql库表结构导出word,你学Fei了吗?

不宅的技术猿 256

前言:

目前看官们对“mysql数据库导出er图”都比较重视,咱们都想要分析一些“mysql数据库导出er图”的相关内容。那么小编同时在网摘上搜集了一些对于“mysql数据库导出er图””的相关内容,希望同学们能喜欢,你们一起来了解一下吧!

还在苦恼于在word中写表结构吗今天,它来了一键生成,再无忧虑先上效果图

导出效果图

代码目录

代码目录

python代码connectionDB.py

import pymysqlclass SQLgo(object):    def __init__(self, ip=None, user=None, password=None, db=None, port=None):        self.ip = ip        self.user = user        self.password = password        self.db = db        self.port = int(port)        self.con = object    @staticmethod    def addDic(theIndex, word, value):        theIndex.setdefault(word, []).append(value)    def __enter__(self):        self.con = pymysql.connect(            host=self.ip,            user=self.user,            passwd=self.password,            db=self.db,            charset='utf8mb4',            port=self.port        )        return self    def __exit__(self, exc_type, exc_val, exc_tb):        self.con.close()    def search(self, sql=None):        data_dict = []        id = 0        with self.con.cursor(cursor=pymysql.cursors.DictCursor) as cursor:            sqllist = sql            cursor.execute(sqllist)            result = cursor.fetchall()            for field in cursor.description:                if id == 0:                    data_dict.append({'title': field[0], "key": field[0], "fixed": "left", "width": 150})                    id += 1                else:                    data_dict.append({'title': field[0], "key": field[0], "width": 200})            len = cursor.rowcount        return {'data': result, 'title': data_dict, 'len': len}    def showtable(self, table_name):        with self.con.cursor() as cursor:            sqllist = '''                    select aa.COLUMN_NAME,                    aa.DATA_TYPE,aa.COLUMN_COMMENT, cc.TABLE_COMMENT                     from information_schema.`COLUMNS` aa LEFT JOIN                     (select DISTINCT bb.TABLE_SCHEMA,bb.TABLE_NAME,bb.TABLE_COMMENT                     from information_schema.`TABLES` bb ) cc                      ON (aa.TABLE_SCHEMA=cc.TABLE_SCHEMA and aa.TABLE_NAME = cc.TABLE_NAME )                    where aa.TABLE_SCHEMA = '%s' and aa.TABLE_NAME = '%s';                    ''' % (self.db, table_name)            cursor.execute(sqllist)            result = cursor.fetchall()            td = [                {                    'Field': i[0],                    'Type': i[1],                    'Extra': i[2],                    'TableComment': i[3]                } for i in result            ]        return td    def gen_alter(self, table_name):        with self.con.cursor() as cursor:            sqllist = 'desc %s.%s;' % (self.db, table_name)            cursor.execute(sqllist)            result = cursor.fetchall()            td = [                {                    'Field': i[0],                    'Type': i[1],                    'Null': i[2],                    'Key': i[3],                    'Default': i[4]                } for i in result            ]            sqllist = 'show table status where NAME="%s";' % (table_name)            cursor.execute(sqllist)            result = cursor.fetchall()            tablecomment = result[0][-1]            [item.update(TableComment=tablecomment) for item in td]            sqllist = 'show full columns from %s;' % (table_name)            cursor.execute(sqllist)            result = cursor.fetchall()            for item in td:                for item1 in result:                    if item['Field'] == item1[0]:                        item['Extra'] = item1[-1]                        break        return td    def index(self, table_name):        with self.con.cursor() as cursor:            cursor.execute('show keys from %s' % table_name)            result = cursor.fetchall()            di = [                {                    'Non_unique': '是',                    'key_name': i[2],                    'column_name': i[4],                    'index_type': i[10]                }                if i[1] == 0                else                {                    'Non_unique': '否',                    'key_name': i[2],                    'column_name': i[4],                    'index_type': i[10]                }                for i in result            ]            dic = {}            c = []            for i in di:                self.addDic(dic, i['key_name'], i['column_name'])            for t in dic:                """                初始化第一个value                将value 数据变为字符串                转为字典对象数组                """                str1 = dic[t][0]                for i in range(1, len(dic[t])):                    str1 = str1 + ',' + dic[t][i]                temp = {}                for g in di:                    if t == g['key_name']:                        temp.setdefault('Non_unique', g['Non_unique'])                        temp.setdefault('index_type', g['index_type'])                temp.setdefault('column_name', str1)                temp.setdefault('key_name', t)                c.append(temp)            return c    def baseItems(self, sql=None):        with self.con.cursor() as cursor:            cursor.execute(sql)            result = cursor.fetchall()            data = [c for i in result for c in i]            return data    def query_info(self, sql=None):        with self.con.cursor(cursor=pymysql.cursors.DictCursor) as cursor:            cursor.execute(sql)            result = cursor.fetchall()        return result
generateWord.py
#!/usr/bin/env python3# coding=utf-8from docx import Documentfrom docx.oxml.ns import qnfrom docx.shared import Ptimport timeimport connectionDBdef generateDB2Word(ip, user, password, port='3306', db='', tgtPath="/"):    start = time.time()    targetDoc = Document()    targetDoc.styles['Normal'].font.name = u'宋体'    targetDoc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')    targetHead = ['序号', "字段名称", '数据类型', '长度', '主/外键', '可空', '字段说明', '默认值']    with connectionDB.SQLgo(            ip=ip,            user=user,            password=password,            port=port,            db=db    ) as f:        tables = f.baseItems(sql='show tables')        for table in tables:            # 设置标题 级别5            tbt = targetDoc.add_heading(level=5)            tbtRun = tbt.add_run(table)            tbtRun.font.size = Pt(12)            tbtRun.font.name = 'Times New Roman'            tbtRun.font.bold = True            # 新增表格            targetTable = targetDoc.add_table(rows=1, cols=len(targetHead))            targetTable.autofit = True            targetTable.style = 'Table Grid'            targetTable.style.font.size = Pt(10)            targetTable.style.font.name = '宋体'            # 设置表头            titleCells = targetTable.rows[0].cells            for i in range(len(targetHead)):                titleCells[i].text = targetHead[i]                runCell = titleCells[i].paragraphs[0].runs[0]                runCell.font.bold = True            # 填充内容            fields = f.gen_alter(table_name=table)            for num in range(0, len(fields)):                newCells = targetTable.add_row().cells                newCells[0].text = str(num + 1)                newCells[1].text = fields[num]['Field']                if '(' in fields[num]['Type']:                    typeLenArray = fields[num]['Type'][0: -1].split('(')                    newCells[2].text = typeLenArray[0]                    newCells[3].text = typeLenArray[1]                else:                    newCells[2].text = fields[num]['Type']                if fields[num]['Key'] == 'PRI':                    newCells[4].text = 'PK'                if fields[num]['Null'] == 'YES':                    newCells[5].text = 'Y'                else:                    newCells[5].text = 'N'                newCells[6].text = str(fields[num]['Extra']).replace('None', '')                newCells[7].text = str(fields[num]['Default']).replace('None', '')        targetDoc.save(tgtPath)    end = time.time()    print('运行完成, 耗时: ' + str(int(end - start)) + 's')
main.py
from generateWord import generateDB2Wordif __name__ == '__main__':    generateDB2Word(ip='127.0.0.1',                    user="root",                    password="123456",                    port="3306",                    db="test",                    tgtPath='E:\\test.docx')
解析主要配置在main.py中db是需要导出的数据库tgtPath是需要导出到哪个路径

标签: #mysql数据库导出er图