前言
由于最近遇到一个实体类有特别多的字段,我就想自己一个地在表中创建,并写注释未免太浪费人力和时间了,然后在网上查找资料,果不其然让我看到了一个可以使用Python读取excel内容追加到mysql表中赋予字段注释,这简直是他好了
正文
1、首先你的把你的实体类所有的字段保存到一个新的excel表中,统一放到一行中
问题: 如何把你的实体类所有的字段保存到一个新的excel表?
答: 你得有个vs Code工具,将实体类的代码粘贴上去,然后利用快捷键shfit + alt 把多余的删掉
然后把他们放到一个excel表中
在一个空格右键选择性粘贴->转置
出来了
2、然后在navicat把它导入进去
…这里不贴了,你改下字段类型即可
3、Python读取excel内容追加到mysql表中赋予字段注释
这里又要新开个excel表了喔,用来存你刚刚创好的字段、表名,然后你就在这里写入每个字段的注释即可
以下是这篇文章的主要的代码(建议直接复制粘贴,当然你的数据库名字、密码、账号、表名你都要修改):
import openpyxl
import os
import pymysql
import pdb
hostname = '127.0.0.1'
uname = 'root'
pword = 'root'
# 以追加的形式打印出建表sql和需要加注释的sql
def writeFile(content: str):
with open('aa', 'a') as f:
f.write('{} \n'.format(content))
# 连接数据库,获取建表sql
def getTableSql(tablename):
conn = pymysql.connect(host=hostname, port=3306, user=uname, password=pword, database='iec104')
res = None
try:
cursor = conn.cursor()
cursor.execute('show create table {}'.format(tablename))
_, res = cursor.fetchone()
except pymysql.Error as err:
print(err)
finally:
cursor.close()
conn.close()
return res
# 替换sql部分 匹配到相关行 后面加上注释。因为用的逗号分隔 考虑到decimal(m,n)这种情况,所以第一段匹配后,要加上后面的再加注释,所以用flag来标识。
def replaceSql(createsql, fieldvalue, fielddesc, tablename, isfirst):
if createsql is None or createsql == '' or 'exist' in createsql or str(fieldvalue).lower() == 'id':
return
# pdb.set_trace()
lsql = createsql.split(',')
# print(lsql)
col = '`{}`'.format(fieldvalue.lower())
desc = "comment '{}'".format(fielddesc)
altertab = ''
decimalproc = ''
decimalflag = False
if isfirst == 1:
altertab = ' alter table {} '.format(tablename)
else:
altertab = ''
altersql = ''
for isql in lsql:
if decimalflag:
altersql = '{} ,{} {},'.format(altersql, isql, desc)
decimalflag = False
break
if col in isql:
# if col == 'discount_amount':
# pdb.set_trace()
if 'decimal' in isql:
# decimal process two line
# pdb.set_trace()
decimalflag = True
altersql = '{} modify {} '.format(altertab, isql)
else:
altersql = '{} modify {} {},'.format(altertab, isql, desc)
break
print(altersql)
writeFile(altersql)
# 接下来是读excel 区分是读表名 或 列名
def readExcel(fpath):
''' read sheet1 file contents:
row1 col1 'tablename' col2 tablename col3 describtion
row2 fields fieldsdescribtion demo
real content....
space
row1 col1 'tablename' col2 tablename col3 describtion
....
can igore fiedl3
'''
readwb = openpyxl.load_workbook(fpath)
# read sheet1 default
ws = readwb.active
col = 1 # column number in Excel
isfirst = 1 # table first column
createsql = '' # create sql statement
tablename = '' # tablename
for row in range(1, ws.max_row + 1):
print(row)
# pdb.set_trace()
col = 1
evaluecoo = ws.cell(row=row, column=col).value
if str(evaluecoo).strip() is None or str(evaluecoo).strip() == '':
createsql = ''
tablename = ''
isfirst = 1
elif str(evaluecoo).strip() == '字段':
continue
elif str(evaluecoo).strip() == '表名':
col += 1
evaluecot = ws.cell(row=row, column=col).value
# connect db get create table sql
tablename = evaluecot
createsql = getTableSql(evaluecot)
# write create sql to file
if createsql is None:
writeFile('\n table is not found {}'.format(tablename))
else:
writeFile(createsql)
else:
fieldvalue = ws.cell(row=row, column=col).value
fielddesc = ws.cell(row=row, column=col + 1).value
# add alter table statement
# skip fielddesc None
if fielddesc is None or str(fielddesc).strip() == '':
continue
# add alter table statement
replaceSql(createsql, fieldvalue, fielddesc, tablename, isfirst)
# skip id
if str(fieldvalue).lower() == 'id':
isfirst = 1
else:
isfirst = 0
# 程序开始执行
if __name__ == '__main__':
readExcel('./ss.xlsx')
问题:可能你会遇到openpyxl、pymysql爆红,点这里搜名字下载即可
效果:
参考:
https://blog.csdn.net/haohaojiuhao123/article/details/104389054
https://blog.csdn.net/python_xep/article/details/115477755?spm=1001.2014.3001.5506