目录

一,连接数据库

下载pymysql软件包的三种方式

方式一

方式二

方式三

新建util包和DBUtil类,完整代码如下

二,模块搭建

建立实体类book

三,界面搭建

新建main包GUI文件

四,功能完成

新建dao包 bookdao文件

GUI完整代码如下

五,运行效果演示


一,连接数据库

下载pymysql软件包的三种方式

方式一

输入import mymysql,根据提示点击即可安装

方式二

win+r打开黑窗口,执行 pip install pymysql 命令

方式三

文件--->设置--->项目--->python解释器--->+--->搜索pymysql--->安装

连接数据库

新建util包和DBUtil类,完整代码如下

import pymysql


# 帮助类

class DbUtil:
    conn: object
    cursor: object

    def __init__(self):
        # 开启连接 得到游标对象
        self.conn = pymysql.connect(host='localhost', port=3306,
                                    user='root', password='root123',
                                    database='ruyi_vue', charset='utf8')
        self.cursor = self.conn.cursor()

    def execute(self, sql: str, val: tuple = None):
        self.cursor.execute(sql, val)
        self.connmit()

    def execute_list(self, sql: str):
        self.cursor.execute(sql, None)
        return self.cursor.fetchall()

    def close(self):
        self.cursor.close()
        self.conn.close()

 注意:

        # 开启连接 得到游标对象
        self.conn = pymysql.connect(host='主机名称', port=端口号,
                                    user='用户名', password='密码',
                                    database='数据库名', charset='编码格式') 

是utf8而不是utf-8

二,模块搭建

建立实体类book

# 实体类
# 新建pojo持久对象
class Book:#默认继承objject
    drugsid: int
    name: str
    Specification: str
    unit: str
    description: str
    state: int
    purchase: float
    retail: float

    def __init__(self, drugsid: int = None, name: str = None, Specification: str = None, unit: str = None,
                 description: str = None, state: int = None, purchase: str = None, retail: str = None):
        self.drugsid = drugsid
        self.name = name
        self.Specification = Specification
        self.unit = unit
        self.description = description
        self.state = state
        self.purchase = purchase
        self.retail = retail


    def __str__(self):
        return f"{self.drugsid},{self.name},{self.Specification},{self.unit},{self.description},{self.state},{self.purchase},{self.retail}"


if __name__ == '__main__':
    b = Book(drugsid=1)
    print(b)

三,界面搭建

新建main包GUI文件

新建界面

window = Tk()

调整页面大小

window.geometry('800x500')

新建表格

table = Treeview(columns=('drugsid', 'name', 'Specification', 'unit', 'description', 'state', 'purchase', 'retail'),
                 show="headings")
table.column('drugsid', width=100)
table.column('name', width=100)
table.column('Specification', width=100)
table.column('unit', width=100)
table.column('description', width=100)
table.column('state', width=100)
table.column('purchase', width=100)
table.column('retail', width=100)
table.heading('drugsid', text='药品编号')
table.heading('name', text='药品名称')
table.heading('Specification', text='单位')
table.heading('unit', text='药品单位')
table.heading('description', text='主治功能')
table.heading('state', text='状态')
table.heading('purchase', text='进价')
table.heading('retail', text='售价')

让表格显示

table.place(width=800, height=300)

让界面显示

window.mainloop()

四,功能完成

新建dao包 bookdao文件

编写查询,增加,删除的方法,完整代码如下

from util.DBUtil import DbUtil
from pojo.book import Book


class BookDao:
    bu: DbUtil

    def __init__(self):
        self.bu = DbUtil()

    def add_book(self, b: Book):
        try:
            assert isinstance(self.bu, DbUtil)
            # 只支持 %s 占位符
            # %s 支持任意类型
            self.bu.execute('insert into t_medical_drugs_info values(null,%s,%s,%s,%s,%s,%s,%s)',
                            (b.name, b.Specification, b.unit, b.description, b.state, b.purchase, b.retail))
            return '操作成功'
        except Exception as e:
            print(e)
            return '操作失败'

    def del_book(self, b: Book):
        try:
            assert isinstance(self.bu, DbUtil)
            # 只支持 %s 占位符
            # %s 支持任意类型
            self.bu.execute('delete from t_medical_drugs_info where drugsid=%s',
                            (b.drugsid))
            return '操作成功'
        except Exception as e:
            print(e)
            return '操作失败'

    def list_book(self, page: int = 1, rows: int = 10):
        try:
            assert isinstance(self.bu, DbUtil)
            start = (page - 1) * rows + 1
            return self.bu.execute_list('select * from t_medical_drugs_info limit %d,%d'
                                        % (start, rows))
        except Exception as e:
            print(e)
            return '操作失败'


if __name__ == "__main__":
    bd = BookDao()
    r = bd.list_book(page=3)
    print(r)

在GUI界面,调用查询,增加,删除的方法

def load():
    # 清除表格的数据
    for i in table.get_children():
        table.delete(i)
    # 先读出数据库的数据
    for i in bd.list_book():
        # 将数据加入到表格中
        table.insert('', END, value=i)


def add():
    name = askstring('提示', '请输入药品名称')
    Specification = askstring('提示', '请输入单位')
    unit = askstring('提示', '请输入药品单位')
    description = askstring('提示', '请输入主治功能')
    state = askinteger('提示', '请输入状态(1/2)')
    purchase = askfloat('提示', '请输入进货单价')
    retail = askfloat('提示', '请输入零售单价')
    if name is not None:
        r = bd.add_book(Book(name=name,Specification=Specification,unit=unit,description=description,state=state,purchase=purchase,retail=retail))
        messagebox.showerror(r)


def delete():
    if messagebox.askyesno('提示','是否删除'):
     ids = []
    # 制作多选删除
    for i in table.selection():
        # i是元素的id
        # item 根据id拿对应的数据
        ids.append(table.item(i)['values'][0])
    if len(table.selection()) == 0:
        drugsid = askinteger('提示', '请输入药品编号')
        ids.append(drugsid)
    for i in ids:
        bd.del_book(Book(drugsid=i))


Button(text='加载', command=load).place(x=200, y=350)
Button(text='增加', command=add).place(x=400, y=350)
Button(text='删除', command=delete).place(x=600, y=350)

GUI完整代码如下

# 导入界面模块
from tkinter import *
# 导入表格模具
from tkinter.ttk import Treeview
# 导入dao层
from dao.bookdao import BookDao
# 导入弹框
from tkinter.simpledialog import *
# 导入提示框
from tkinter.messagebox import *

from pojo.book import Book

bd = BookDao()
# 新建界面
window = Tk()
# 调整页面的大小 widthxheight+x+y
window.geometry('800x500')

# 新建一个表格
table = Treeview(columns=('drugsid', 'name', 'Specification', 'unit', 'description', 'state', 'purchase', 'retail'),
                 show="headings")
table.column('drugsid', width=100)
table.column('name', width=100)
table.column('Specification', width=100)
table.column('unit', width=100)
table.column('description', width=100)
table.column('state', width=100)
table.column('purchase', width=100)
table.column('retail', width=100)
table.heading('drugsid', text='药品编号')
table.heading('name', text='药品名称')
table.heading('Specification', text='单位')
table.heading('unit', text='药品单位')
table.heading('description', text='主治功能')
table.heading('state', text='状态')
table.heading('purchase', text='进价')
table.heading('retail', text='售价')

def load():
    # 清除表格的数据
    for i in table.get_children():
        table.delete(i)
    # 先读出数据库的数据
    for i in bd.list_book():
        # 将数据加入到表格中
        table.insert('', END, value=i)


def add():
    name = askstring('提示', '请输入药品名称')
    Specification = askstring('提示', '请输入单位')
    unit = askstring('提示', '请输入药品单位')
    description = askstring('提示', '请输入主治功能')
    state = askinteger('提示', '请输入状态(1/2)')
    purchase = askfloat('提示', '请输入进货单价')
    retail = askfloat('提示', '请输入零售单价')
    if name is not None:
        r = bd.add_book(Book(name=name,Specification=Specification,unit=unit,description=description,state=state,purchase=purchase,retail=retail))
        messagebox.showerror(r)


def delete():
    if messagebox.askyesno('提示','是否删除'):
     ids = []
    # 制作多选删除
    for i in table.selection():
        # i是元素的id
        # item 根据id拿对应的数据
        ids.append(table.item(i)['values'][0])
    if len(table.selection()) == 0:
        drugsid = askinteger('提示', '请输入药品编号')
        ids.append(drugsid)
    for i in ids:
        bd.del_book(Book(drugsid=i))


Button(text='加载', command=load).place(x=200, y=350)
Button(text='增加', command=add).place(x=400, y=350)
Button(text='删除', command=delete).place(x=600, y=350)

# 让表格显示
table.place(width=800, height=300)
# 让界面显示
window.mainloop()

五,运行效果演示

 点击加载

 点击增加,依次填入字段的值

 选中一行数据,点击删除

点击是,再次刷新数据被删除 

更多推荐

python之连接MySQL数据库的简易界面编程(连接数据库+模块搭建+界面搭建+功能完成+效果演示)