• 主页

  • 投资

  • IT

    🔥
  • 设计

  • 销售

关闭

返回栏目

关闭

返回python栏目

122 - 小工具 - mysql数据库设计转word

作者:

贺及楼

成为作者

更新日期:2024-05-30 12:12:49

mysql数据库设计转word

mysql数据库设计转word 介绍

  1. 3个类:
  2. 一个是数据库类 = SQL()
  3. 一个是word文档类 = WORD()
  4. 一个是逻辑类 = Main()
  5. 先用Main().list()方法找到要跑的表
  6. 也可以全部表复制进去
  7. 如果一条记录都没有的,不写入表

代码

  1. # -*- coding: utf-8 -*-
  2. import json
  3. from textwrap import indent
  4. import pymysql
  5. from sqlalchemy import create_engine
  6. import docx
  7. import pandas as pd
  8. import numpy as np
  9. class SQL():
  10. def __init__(self):
  11. self.ip = "ip"
  12. self.port = "3306"
  13. self.port2 = 3306
  14. self.username = "root"
  15. self.secret = "secret"
  16. self.dbname = "dbname"
  17. # self.tablename = "tablename"
  18. def connect(self):
  19. url = 'mysql+pymysql://'+self.username+':'+self.secret+'@'+self.ip+':'+self.port+'/'+self.dbname+'?charset=utf8mb4'
  20. print(url)
  21. connect = create_engine(url)
  22. return connect
  23. def connect2(self):
  24. db = pymysql.connect(host=self.ip, user=self.username, password=self.secret, port=self.port2,database=self.dbname)
  25. cursor = db.cursor() # 获得指针
  26. return cursor
  27. def select(self):
  28. cursor = self.connect2()
  29. sql = 'select * from dbname.tablename;'
  30. cursor.execute(sql) # 执行
  31. return cursor
  32. def all_tables(self):
  33. cursor = self.connect2()
  34. sql = "use "+self.dbname+";"
  35. cursor.execute(sql) # 执行
  36. sql = "show tables;"
  37. cursor.execute(sql) # 执行
  38. return list(cursor)
  39. def select_desc(self, table_name):
  40. cursor = self.connect2()
  41. sql = "desc "+table_name+";"
  42. cursor.execute(sql) # 执行
  43. return cursor
  44. def select_one(self, table_name):
  45. try:
  46. cursor = self.connect2()
  47. sql = "select * from "+table_name+" where id = 1;"
  48. cursor.execute(sql) # 执行
  49. data = cursor.fetchall()
  50. cols = cursor.description
  51. data = list(data)
  52. print('cols')
  53. print(cols)
  54. print('cols')
  55. return data, cols
  56. except:
  57. return [], []
  58. class WORD():
  59. def __init__(self):
  60. print("")
  61. def doc(self):
  62. doc = docx.Document()
  63. return doc
  64. def write_table(self, doc, df):
  65. t = doc.add_table(df.shape[0]+1, df.shape[1])
  66. # print(df)
  67. # add the header rows.
  68. for j in range(df.shape[-1]):
  69. t.cell(0,j).text = str(df.columns[j])
  70. # add the rest of the data frame
  71. for i in range(df.shape[0]):
  72. for j in range(df.shape[-1]):
  73. t.cell(i+1,j).text = str(df.values[i,j])
  74. return
  75. # save the doc
  76. def write_dict(self, doc, data):
  77. data = data.to_dict('records')
  78. data_str = json.dumps(data,indent=2, default=str,ensure_ascii=False)
  79. p3 = doc.add_paragraph()
  80. p3.add_run(data_str)
  81. def save(self, doc):
  82. doc.save('./test.docx')
  83. class Main():
  84. def __init__(self):
  85. self.table_list = ['user','student'] # 修改需要生成的表
  86. def list(self):
  87. table_list = SQL().all_tables()
  88. table_list_T = []
  89. for i in table_list:
  90. table_list_T.append(i[0])
  91. return table_list_T
  92. def run(self):
  93. Sql = SQL()
  94. Word = WORD()
  95. doc = Word.doc() # 新文档
  96. for i in self.table_list:
  97. desc_data = Sql.select_desc(i)
  98. desc_data = pd.DataFrame(data=desc_data)
  99. one_data, cols = Sql.select_one(i)
  100. col = []
  101. for c in cols:
  102. col.append(c[0])
  103. one_data = pd.DataFrame(data=one_data, columns=col)
  104. print(one_data)
  105. # if one_data==[]:
  106. if one_data.empty:
  107. continue
  108. desc_data["解释"] = ""
  109. desc_data.columns = ["名字","类型","必填","主键","默认","附加","解释"]
  110. p3 = doc.add_paragraph()
  111. p3.add_run(i)
  112. Word.write_table(doc, desc_data)
  113. Word.write_dict(doc, one_data)
  114. Word.save(doc)
  115. if __name__=="__main__":
  116. # 全部列表,然后要贴到Main()的self.table_list
  117. # table_list = Main().list()
  118. # print(table_list)
  119. Main().run()