1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| import pymysql from docxtpl import DocxTemplate
def getTableMetadata(host, user, password, dbName): conn = pymysql.connect(host=host, user=user, password=password, database=dbName) cursor = conn.cursor()
cursor.execute("SELECT TABLE_NAME, TABLE_COMMENT FROM information_schema.tables WHERE TABLE_SCHEMA = %s;", (dbName,)) tables = cursor.fetchall()
metadata = []
for table in tables: tableName = table[0] tableRemark = table[1] cursor.execute(f"SHOW FULL COLUMNS FROM {tableName};") columns = cursor.fetchall()
columnList = [] for column in columns: columnInfo = { "name": column[0], "type": column[1], "key": column[4], "empty": column[3], "default": column[5] if column[5] is not None else "", "remark": column[8] if column[8] else "" } columnList.append(columnInfo)
cursor.execute(f"SHOW INDEX FROM {tableName};") indexes = cursor.fetchall()
indexDict = {} for index in indexes: keyName = index[2] columnName = index[4] nonUnique = index[1] seqInIndex = index[3] indexType = index[10]
if keyName not in indexDict: indexDict[keyName] = { "nonUnique": "YES" if nonUnique else "NO", "seqInIndex": seqInIndex, "indexType": indexType, "columns": [] } indexDict[keyName]["columns"].append(columnName)
indexList = [] for keyName, indexInfo in indexDict.items(): indexList.append({ "keyName": keyName, "columns": ", ".join(indexInfo["columns"]), "nonUnique": indexInfo["nonUnique"], "seqInIndex": indexInfo["seqInIndex"], "indexType": indexInfo["indexType"] })
tableInfo = { "name": tableName, "remark": tableRemark, "list": columnList, "indexList": indexList } metadata.append(tableInfo)
conn.close() return metadata
def main(): host = "192.168.1.145" user = "root" password = "123456" dbName = "db_sovecloud_mgr"
tablesMetadata = getTableMetadata(host, user, password, dbName)
context = { "tables": tablesMetadata } template = DocxTemplate("tpl.docx") template.render(context) template.save("output.docx")
if __name__ == "__main__": main()
|