python自动生成sql语句

描述:
工作中在数据库中创建表时,当字段很多时,比较麻烦,开发一个工具,可在excel中写好字段英文名和中文名,然后通过py生成脚本或直接在库中生成表
脚本:

import tkinter
from tkinter import *
import tkinter.messagebox
from tkinter import scrolledtext
import xlrd
import pymysql
import os

#从excel中获取字段项,组合建表语句
def get_create_sql(dir_path, file_name):
    try:
        # 打开xls文件
        #excel_path = "%s%s" % (dir_path, file_name)
        #print("excel_path:",excel_path)
        wb = xlrd.open_workbook(filename=dir_path)
        # 打开第一sheet
        ws = wb.sheets()[0]
        #获取行列数量
        nrows = ws.nrows
        #ncols = ws.ncols
        #获取sheet1的名称
        table_name = ws.name
        #print("nrows:",nrows)
        #print("ncols:",ncols)
        #print("sheet1_name:",table_name)
        #xlrd中行列是从0开始的
        for i in range(nrows):
            if i == 0: #字段英文,格式是列表
                row0_data = ws.row_values(0)
                #print(row0_data)
            if i == 1: #字段中文,格式是列表
                row1_data = ws.row_values(1)
                #print(row1_data)
        #将含有-字符的替换
        header0 = [str(i).replace("-", "_").replace("-", "_").replace("(", "_").replace(")", "") for i in row0_data]
        #print("header0:",header0)
        header1 = [str(i).replace("-", "_").replace("-", "_").replace("(", "_").replace(")", "") for i in row1_data]
        #print("header1:",header1)
        #获取表名
        table_commet = file_name.split(".")[0]
        #print("table_name:",table_name)
        create_sql = "CREATE TABLE `%s` (\n" % table_name
        #print("create_sql:",create_sql)
        header0_len = len(header0)
        #print("header0_len:",header0_len)
        for i in range(header0_len):
            #print("i:", i,"value:",header0[i])
            if i < header0_len-1:
                create_sql += "`%s` varchar(255) DEFAULT NULL COMMENT '%s',\n" % (header0[i], header1[i])
            if i == header0_len-1:
                create_sql += "`%s` varchar(255) DEFAULT NULL COMMENT '%s'\n" % (header0[i], header1[i])
        create_sql += ") ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='%s';\n" % table_commet
        #print("[INFO]:[create_sql]", create_sql)
    except BaseException as e:
        #print("[ERRO]:", str(e))
        tkinter.messagebox.showerror('错误', str(e))
    return create_sql

def to_db(create_sql,hostname,hostport,username,userpasswd,dbname):
    #链接数据库,执行
    #print(hostname,hostport,username,userpasswd,dbname)
    try:
        db = pymysql.connect(host=hostname, port=hostport, user=username, passwd=userpasswd, db=dbname)
        cursor = db.cursor()
        cursor.execute(create_sql)
        cursor.fetchall()
        db.close()
        #print("表创建成功!")
        tkinter.messagebox.showinfo('提示', '表创建成功 !')
    except BaseException as e:
        #print("表创建失败!", str(e))
        tkinter.messagebox.showerror('错误', str(e))

# get 变量内容
def show_db():
    if v1.get() == '' or v2.get() == '' or v3.get() == '' or v4.get() == '' or v5.get() == '' or v6.get() == '':
        tkinter.messagebox.showinfo('提示', '请先输入内容 !')
        return
    if v1.get() == 'token**123':
        tkinter.messagebox.showinfo('提示', 'author by lijiyan 2020-12-03,Thank you.')
        return
    #print("文件路径名 :%s" % e1.get())
    #print("数据库IP :%s" % e2.get())
    #print("数据库端口 :%s" % e2.get())
    #print("库名 :%s" % e2.get())
    #print("用户名 :%s" % e2.get())
    #print("密码 :%s" % e2.get())
    #easygui.msgbox('执行完成 !')
    dir_pathname = e1.get()
    #dir_pathi = os.path.dirname(dir_pathname)
    file_namei = os.path.basename(dir_pathname)
    #print(dir_pathname,file_namei)

    create_sql = get_create_sql(dir_path=dir_pathname,
                                file_name=file_namei
                                )

    to_db(create_sql=create_sql,
          hostname=e2.get(),
          hostport=int(e3.get()),
          dbname=e4.get(),
          username=e5.get(),
          userpasswd=e6.get()
          )

def show_sql():
    if v1.get() == '':
        tkinter.messagebox.showinfo('提示', '请先输入内容 !')
        return
    #print("文件路径名 :%s" % e1.get())
    dir_pathname = e1.get()
    # dir_pathi = os.path.dirname(dir_pathname)
    file_namei = os.path.basename(dir_pathname)
    # print(dir_pathname,file_namei)

    create_sql = get_create_sql(dir_path=dir_pathname,
                                file_name=file_namei
                                )
    #tkinter.messagebox.showinfo('提示', create_sql)
    t.delete(1.0, END)
    t.insert('insert', create_sql)
    #e8.insert('insert',create_sql)
    #这个可以,但样式难看
    #Label(top, text=create_sql,wraplength=200).grid(row=8,column=0,sticky=W+E+N+S,padx=5,pady=5,rowspan=7,columnspan=2)

#初始框的声明
top = tkinter.Tk()
top.title("生成createsql工具v1.0")
top.geometry("400x300+300+200")
## 标签控件,对Label内容进行 表格式 布局
Label(top,text='文件路径名 :').grid(row=0, column=0)
Label(top,text='数据库IP :').grid(row=2,column=0)
Label(top,text='数据库端口 :').grid(row=3,column=0)
Label(top,text='库名 :').grid(row=4,column=0)
Label(top,text='用户名 :').grid(row=5,column=0)
Label(top,text='密码 :').grid(row=6,column=0)
#Label(top,text='sql :').grid(row=0,column=1)
#定义变量
v1 = StringVar()
v2 = StringVar()
v3 = StringVar()
v4 = StringVar()
v5 = StringVar()
v6 = StringVar()
#v8 = StringVar()
# 输入控件,用于储存 输入的内容
e1 = Entry(top, textvariable=v1)
e2 = Entry(top, textvariable=v2)
e3 = Entry(top, textvariable=v3)
e4 = Entry(top, textvariable=v4)
e5 = Entry(top, textvariable=v5)
e6 = Entry(top, textvariable=v6, show="*")
#e8 = Entry(top, textvariable=v8)

# 进行表格式布局
e1.grid(row=0,column=1,padx=10,pady=5)
e2.grid(row=2,column=1,padx=10,pady=5)
e3.grid(row=3,column=1,padx=10,pady=5)
e4.grid(row=4,column=1,padx=10,pady=5)
e5.grid(row=5,column=1,padx=10,pady=5)
e6.grid(row=6,column=1,padx=10,pady=5)
#e8.grid(row=0,column=2,sticky=W+E+N+S,padx=5,pady=5,rowspan=7,columnspan=2)

#文本内容较大,滚动文本框,展示文本内容
t = scrolledtext.ScrolledText(top,width = 20,height = 20,wrap=WORD)
t.grid(row=0,column=2,rowspan=7,columnspan=2)

# 设置 button 指定 宽度 , 并且 关联 函数 , 使用表格式布局 .
Button(top,text='生成sql',width=10,command=show_sql).grid(row=1,column=1,sticky=E,padx=10,pady=5)
Button(top,text='入库',width=10,command=show_db).grid(row=7,column=1,sticky=W,padx=10,pady=5)
Button(top,text='退出',width=10,command=top.quit).grid(row=7,column=1,sticky=E,padx=10,pady=5)

mainloop()

打包生成工具:
在资源栏

excel说明:
第一行,表字段英文名称
第二行,表字段中文名称
第三行,表数据,可不写

你可能感兴趣的:(python,python,mysql,数据库)