首页 > 数据库 >Python练手小项目——简易版基础SQL模板代码生成器

Python练手小项目——简易版基础SQL模板代码生成器

时间:2023-07-15 19:22:18浏览次数:38  
标签:练手 代码生成 Python frame db height width sql tb

1、效果图

2、代码

源码-ui.py

from tkinter import *
from tkinter import scrolledtext, messagebox
from tkinter.ttk import Combobox
import pymysql




def init():
    # 创建窗口:实例化一个窗口对象
    window = Tk()

    # 窗口大小
    window.geometry("900x550")

    #  窗口标题
    window.title("基础SQL语句代码生成器")

    frame = Frame(window, relief=SUNKEN, borderwidth=2, width=450, height=250)
    frame.pack(side=TOP, fill=BOTH, expand=1)

    titleLabel = Label(frame, text="数据库连接", fg="red", font=("Arial Bold", 14))
    titleLabel.place(x=400, y=20, width=150, height=30)

    ipLabel = Label(frame, text="IP:", fg="red", font=("Arial Bold", 10))
    ipLabel.place(x=250, y=60, width=50, height=30)
    ipVar = StringVar()
    ipVar.set("localhost")
    ipEntryBox = Entry(frame, width=50, textvariable=ipVar)
    ipEntryBox.focus()  # 自动聚焦
    # 设置放置的位置
    ipEntryBox.place(x=300, y=60, width=300, height=30)

    portLabel = Label(frame, text="端口:", fg="red", font=("Arial Bold", 10))
    portLabel.place(x=250, y=100, width=50, height=30)
    portVar = IntVar()
    portVar.set(3306)
    portEntryBox = Entry(frame, width=50, textvariable=portVar)
    # 设置放置的位置
    portEntryBox.place(x=300, y=100, width=300, height=30)

    dbLabel = Label(frame, text="数据库:", fg="red", font=("Arial Bold", 10))
    dbLabel.place(x=250, y=140, width=50, height=30)
    dbVar = StringVar()
    dbVar.set("hello")
    dbEntryBox = Entry(frame, width=50, textvariable=dbVar)
    # 设置放置的位置
    dbEntryBox.place(x=300, y=140, width=300, height=30)

    userLabel = Label(frame, text="用户名:", fg="red", font=("Arial Bold", 10))
    userLabel.place(x=250, y=180, width=50, height=30)
    userVar = StringVar()
    userVar.set("root")
    userEntryBox = Entry(frame, width=50, textvariable=userVar)
    userEntryBox.place(x=300, y=180, width=300, height=30)

    passwordLabel = Label(frame, text="密码:", fg="red", font=("Arial Bold", 10))
    passwordLabel.place(x=250, y=220, width=50, height=30)
    passwordVar = StringVar()
    passwordVar.set("root")
    passwordEntryBox = Entry(frame, width=50, textvariable=passwordVar)
    passwordEntryBox.place(x=300, y=220, width=300, height=30)

    # tipsLabel = Label(frame, text="---", fg="red", font=("Arial Bold", 10))
    # tipsLabel.place(x=400, y=320, width=100, height=30)
    tbCombo = Combobox(frame)
    tbCombo['values'] = ["请选择表名"]
    tbCombo.current(0)
    tbCombo.place(x=200, y=320, width=100, height=30)

    conn = None

    def toConn():
        global conn
        ip = ipEntryBox.get()
        port = int(portEntryBox.get())
        db = dbEntryBox.get()
        userName = userEntryBox.get()
        password = passwordEntryBox.get()
        if ip is None or ip == "":
            messagebox.showwarning('提示', '请输入ip')
            return
        if port is None or port == "":
            messagebox.showwarning('提示', '请输入port')
            return
        if db is None or db == "":
            messagebox.showwarning('提示', '请输入数据库名')
            return
        if userName is None or userName == "":
            messagebox.showwarning('提示', '请输入用户名')
            return
        if password is None or password == "":
            messagebox.showwarning('提示', '请输入密码')
            return

        conn = connMySQL(db=db, host=ip, port=port, user=userName, pwd=password, encode="utf8")
        titleLabel.configure(text="连接已开启!")

        cur = conn.cursor()
        cur.execute("show tables;")
        data = cur.fetchall()
        arr = ["请选择表名"]
        for item in data:
            arr.append(item[0])
        tbCombo['values'] = tuple(arr)

    connBtn = Button(frame, text="开始连接", command=toConn)
    connBtn.place(x=200, y=280, width=100, height=30)

    textArea = scrolledtext.ScrolledText(frame, width=100, height=12, wrap="word", undo=True)
    textArea.place(x=120, y=360)

    def toGen():
        global conn
        if conn is None:
            messagebox.showwarning('提示', '请先连接')
            return
        else:
            db = dbEntryBox.get()
            tb = tbCombo.get()
            sql = "select column_name from information_schema.columns where table_schema='{0}' and table_name='{1}';".format(
                db, tb)
            cur = conn.cursor()
            cur.execute(sql)
            data = cur.fetchall()

            add_sql = concatInsertSQL(db, tb, data)
            textArea.insert(INSERT, add_sql)

            del_sql = concatDeleteSQL(db, tb)
            textArea.insert(INSERT, del_sql)

            update_sql = concatUpdateSQL(db, tb)
            textArea.insert(INSERT, update_sql)

            select_sql = concatSelectSQL(db, tb, data)
            textArea.insert(INSERT, select_sql)

    genBtn = Button(frame, text="开始生成", command=toGen)
    genBtn.place(x=350, y=280, width=100, height=30)


    def resetTxt():
        ipVar.set("localhost")
        portVar.set(3306)
        dbVar.set("hello")
        userVar.set("root")
        passwordVar.set("root")
        titleLabel.configure(text="数据库连接")
        tbCombo['values'] = ("请选择表名",)
        tbCombo.current(0)
        textArea.delete(1.0, END)

    resetBtn = Button(frame, text="重置", command=resetTxt)
    resetBtn.place(x=650, y=280, width=100, height=30)


    def toCloseConn():
        global conn
        if conn is not None:
            closeMySQL(conn)
            resetTxt()

    closeConnBtn = Button(frame, text="断开连接", command=toCloseConn)
    closeConnBtn.place(x=500, y=280, width=100, height=30)


    # 进入消息循环
    window.mainloop()


def connMySQL(db, host="localhost", user="root", pwd="root", port=3306, encode="utf8"):
    return pymysql.connect(host=host, user=user, password=pwd, port=port, database=db, charset=encode)


def closeMySQL(conn):
    conn.close()


def concatInsertSQL(db, tb, data):
    tb_cols = []
    for item in data:
        tb_cols.append(item[0])
    add_sql = "insert into " + str(db) + "." + str(tb) + "("
    for col in tb_cols:
        add_sql += col + ","
    add_sql = add_sql[:-1]
    add_sql += ") values(null" + ("," * (len(tb_cols) - 1)) + "); \n\n\n"
    return add_sql


def concatDeleteSQL(db, tb):
    return "delete from " + str(db) + "." + str(tb) + " where id= ; \n\n\n"


def concatUpdateSQL(db, tb):
    return "update " + str(db) + "." + str(tb) + " \nset  \nwhere   ;\n\n\n"


def concatSelectSQL(db, tb, data):
    tb_cols = []
    for item in data:
        tb_cols.append(item[0])
    select_sql = "select \n  "
    for col in tb_cols:
        select_sql += col + ", "
    select_sql = select_sql[:-2]
    select_sql += "\nfrom " + str(db) + "." + str(tb) + "\nwhere  ;\n\n\n"
    return select_sql



if __name__ == '__main__':
    init()

3、打包


cd 项目目录 

# -F 打包成单独的文件;-D 打包成多个文件
pyinstaller -F -p ./ -i ./icon.ico ./ui.py --noconsole

最终的exe文件在dist目录下。

标签:练手,代码生成,Python,frame,db,height,width,sql,tb
From: https://www.cnblogs.com/cywdder/p/17556726.html

相关文章

  • Python 并发编程之IO模型(转载)
    Python并发编程之IO模型https://www.cnblogs.com/linhaifeng/articles/7454717.htmlIO模型介绍为了更好地了解IO模型,我们需要事先回顾下:同步、异步、阻塞、非阻塞同步(synchronous)IO和异步(asynchronous)IO,阻塞(blocking)IO和非阻塞(non-blocking)IO分别是什么,到底有什么区别......
  • Python 潮流周刊第 11 期(2023-07-15)
    查看全文:Python潮流周刊#11:如何使用Golang运行Python代码?......
  • python打印各种文本颜色及加粗、背景色、斜体、下划线
    ----------字体颜色------------print("\033[1;30m字体颜色:白色\033[0m")print("\033[1;31m字体颜色:红色\033[0m")print("\033[1;32m字体颜色:深黄色\033[0m")print("\033[1;33m字体颜色:浅黄色\033[0m")print("\033[1;34m字体颜色:蓝色\033[0m&quo......
  • python魔术方法属性篇
    python魔术方法属性篇本篇章主要讲与对象的属性有关的魔术方法3,属性篇__getattr____getattribute____setattr____delattr____dir____get____set____delete____slots__ __getattr__方法每当我们写形如这种o.test的代码的时候,我们实际上都是在尝试access这个对象......
  • Python pygame实现中国象棋单机版源码
    今天给大家带来的是关于Python实战的相关知识,文章围绕着用Pythonpygame实现中国象棋单机游戏版展开,文中有非常详细的代码示例,需要的朋友可以参考下#-*-coding:utf-8-*-"""CreatedonSunJun1315:41:562021@author:Administrator"""importpygamefrompygame.local......
  • PHP调用Python无返回或提示No Module
    问题:自己通过命令行执行python正常,但通过php调用就没有反应。解决方法:1、首先检查一下php有没有执行权限,简单粗暴的:sudochmod777xxx.php2、Python如果有中文返回,似乎需要额外操作。可以先去掉中文排除掉其他原因,也可以尝试以下操作:在python文件头部加上importcodecssys.stdout......
  • 【性能测试】性能监控-python编写(CPU | 内存 | 磁盘io)占比监控脚本
    一、主要通过Python脚本实现对linux环境(CPU|内存|磁盘io)监控脚本示例:importtimeimportsubprocess#获取CPU使用率defget_cpu_usage():#系统CPU占比=系统态占比+空闲态占比=3.2%+36.5%=39.7%cpu_usage=subprocess.check_output("top-bn1......
  • Python 20个魔法函数
    本文将为您详细介绍Python中的20个魔法函数,这些函数能够在代码中释放神奇的力量。让我们一起来了解这些特殊的函数,并提供一些在实际接口自动化工作中的示例代码。魔法函数(MagicMethods),也被称为特殊方法或双下划线方法,是Python中一些特殊命名的函数,它们以双下划线开头和结尾......
  • Python学习——Day 6
    流程控制语句break·break语句   ·用于结束循环结构,通常与分支结构if一起使用#输入密码,最多录入3次,如果正确就结束循环foriteminrange(3):pwd=input('请输入密码:')ifpwd=='8888':print('密码正确')breakelse:print('密码......
  • Anaconda-用conda创建python虚拟环境及移植到内网
    conda可以理解为一个工具,也是一个可执行命令,其核心功能是包管理和环境管理。包管理与pip的使用方法类似,环境管理则是允许用户方便滴安装不同版本的python环境并在不同环境之间快速地切换。conda的设计理念conda将几乎所有的工具、第三方包都当作package进行管理,甚至包括python......