Python GUI 窗口实现 MySQL 数据库增删改查功能
这是一个使用 Python 的 tkinter 库创建 GUI 窗口,通过按钮实现对 MySQL 数据库中特定表格的增删改查操作的示例。连接数据库使用 pymysql 库,表格包含姓名、身份证号、性别等信息。
import pymysql
import tkinter as tk
from tkinter import ttk
# 数据库连接参数
HOST = 'localhost'
PORT = 3306
USER = 'root'
PASSWORD = 'password'
DB_NAME = 'test_db'
# 表格字段
FIELDS = ['姓名', '身份证号', '性别', '联系电话', '户籍地址', '警衔', '婚姻状况', '民族', '政治面貌', '年龄']
# 创建数据库连接
conn = pymysql.connect(host=HOST, port=PORT, user=USER, password=PASSWORD, db=DB_NAME)
# 创建窗口
root = tk.Tk()
root.title('数据库操作')
root.geometry('800x600')
# 创建表格控件
table = ttk.Treeview(root, columns=FIELDS, show='headings')
for field in FIELDS:
table.heading(field, text=field)
table.pack()
# 查询数据
def query_data():
# 清空表格中的数据
table.delete(*table.get_children())
# 查询数据库中的数据
cursor = conn.cursor()
cursor.execute('SELECT * FROM test_table')
rows = cursor.fetchall()
# 在表格中显示查询结果
for row in rows:
table.insert('', 'end', values=row)
# 插入数据
def insert_data():
# 获取用户输入的数据
values = []
for field in FIELDS:
value = input(f'请输入{field}: ')
values.append(value)
# 插入数据到数据库中
cursor = conn.cursor()
sql = f"INSERT INTO test_table ({','.join(FIELDS)}) VALUES ({','.join(['%s']*len(FIELDS))})"
cursor.execute(sql, values)
conn.commit()
# 在表格中显示插入结果
table.insert('', 'end', values=values)
# 删除数据
def delete_data():
# 获取用户选中的数据
selected = table.selection()
if len(selected) == 0:
return
# 从数据库中删除选中的数据
cursor = conn.cursor()
for item in selected:
values = table.item(item)['values']
sql = f"DELETE FROM test_table WHERE 姓名=%s AND 身份证号=%s"
cursor.execute(sql, values[:2])
conn.commit()
# 在表格中删除选中的行
for item in selected:
table.delete(item)
# 修改数据
def update_data():
# 获取用户选中的数据
selected = table.selection()
if len(selected) == 0:
return
# 获取用户输入的新数据
new_values = []
for field in FIELDS:
value = input(f'请输入{field}: ')
new_values.append(value)
# 更新数据库中的数据
cursor = conn.cursor()
sql = f"UPDATE test_table SET {','.join([f'{field}=%s' for field in FIELDS])} WHERE 姓名=%s AND 身份证号=%s"
values = new_values + table.item(selected[0])['values'][:2]
cursor.execute(sql, values)
conn.commit()
# 在表格中更新选中的行
table.item(selected[0], values=new_values)
# 创建操作按钮
frame = tk.Frame(root)
frame.pack(pady=10)
btn_query = tk.Button(frame, text='查询', command=query_data)
btn_query.pack(side='left', padx=10)
btn_insert = tk.Button(frame, text='插入', command=insert_data)
btn_insert.pack(side='left', padx=10)
btn_delete = tk.Button(frame, text='删除', command=delete_data)
btn_delete.pack(side='left', padx=10)
btn_update = tk.Button(frame, text='修改', command=update_data)
btn_update.pack(side='left', padx=10)
# 启动窗口
root.mainloop()
# 关闭数据库连接
conn.close()
该示例代码使用 tkinter 库创建 GUI 窗口,并使用 pymysql 库连接 MySQL 数据库。代码包含查询、插入、删除、修改数据的功能,并使用参数化查询防止 SQL 注入攻击。
注意:
- 请将代码中的数据库连接参数修改为您的实际数据库信息。
- 该示例代码仅仅展示基本功能,实际应用中需要根据具体需求进行修改和扩展。
- 建议使用更安全的方式来获取用户输入,例如使用 Entry 控件而不是直接使用 input 函数。
希望该示例代码能帮助您理解如何使用 Python 创建 GUI 应用程序并操作 MySQL 数据库。
原文地址: https://www.cveoy.top/t/topic/n2fd 著作权归作者所有。请勿转载和采集!