项目最终提交

main
miao 9 months ago
parent c14c1cd3a3
commit 48b4e1f84b

@ -0,0 +1,589 @@
import tkinter as tk
from tkinter import messagebox, ttk
import pymysql
# 创建连接
conn = pymysql.connect(
host="localhost",
user="root",
password="123456",
database="online_store"
)
# 创建游标对象
mycursor = conn.cursor()
# 创建Tkinter窗口
root = tk.Tk()
root.title("数据库管理系统")
# 定义角色列表
roles = ["管理员", "商家", "消费者"]
# 定义表名列表
tables = ["User", "Product", "`Order`", "OrderDetail", "Review", "ShoppingCart", "PaymentRecord", "Logistics",
"Warehouse", "Merchant"]
# 获取表格列名
def get_columns(table_name):
mycursor.execute(f"DESCRIBE {table_name}")
return [column[0] for column in mycursor.fetchall()]
# 清除所有标签页
def clear_tabs():
for tab_id in tab_control.tabs():
tab_control.forget(tab_id)
# 增加数据功能(管理员模式)
def add_data():
table_name = tab_add_widgets['table_combobox'].get()
if not table_name:
messagebox.showwarning("警告", "请选择一个表")
return
columns = []
values = []
for column, entry in tab_add_widgets['entry_dict'].items():
value = entry.get().strip()
if value:
columns.append(column)
values.append(value)
if not columns or not values:
messagebox.showwarning("警告", "请输入至少一个列值")
return
try:
query = f"INSERT INTO {table_name} ({', '.join(columns)}) VALUES ({', '.join(['%s'] * len(values))})"
mycursor.execute(query, values)
conn.commit()
messagebox.showinfo("成功", "数据添加成功")
except pymysql.MySQLError as err:
messagebox.showerror("Error", f"Error: {err}")
# 删除数据功能(管理员模式)
def delete_data():
table_name = tab_delete_widgets['table_combobox'].get()
condition_value = tab_delete_widgets['entry_condition'].get().strip()
if not table_name or not condition_value:
messagebox.showwarning("警告", "请选择一个表并输入条件值")
return
# 删除子表中的相关记录
try:
if table_name == "User":
mycursor.execute(f"DELETE FROM Review WHERE {condition_value}")
mycursor.execute(f"DELETE FROM `Order` WHERE {condition_value}")
elif table_name == "Product":
mycursor.execute(f"DELETE FROM Review WHERE {condition_value}")
mycursor.execute(f"DELETE FROM OrderDetail WHERE {condition_value}")
# 删除父表中的记录
mycursor.execute(f"DELETE FROM {table_name} WHERE {condition_value}")
conn.commit()
messagebox.showinfo("成功", "数据删除成功")
except pymysql.MySQLError as err:
messagebox.showerror("Error", f"Error: {err}")
# 更新数据功能(管理员模式)
def update_data():
table_name = tab_update_widgets['table_combobox'].get()
column_name = tab_update_widgets['column_combobox'].get()
new_value = tab_update_widgets['entry_update'].get().strip()
condition_value = tab_update_widgets['entry_condition'].get().strip()
if not table_name or not column_name or not new_value or not condition_value:
messagebox.showwarning("警告", "请选择一个表、列名,并输入新值和条件值")
return
try:
query = f"UPDATE {table_name} SET {column_name} = '{new_value}' WHERE {condition_value}"
mycursor.execute(query)
conn.commit()
messagebox.showinfo("成功", "数据更新成功")
except pymysql.MySQLError as err:
messagebox.showerror("Error", f"Error: {err}")
# 查询数据功能(管理员模式)
def execute_query():
table_name = tab_query_widgets['table_combobox'].get()
if not table_name:
messagebox.showwarning("警告", "请选择一个表")
return
try:
mycursor.execute(f"SELECT * FROM {table_name}")
columns = [desc[0] for desc in mycursor.description]
results = mycursor.fetchall()
# 清空结果区
tab_query_widgets['result_text'].delete("1.0", tk.END)
# 显示列名
tab_query_widgets['result_text'].insert(tk.END, f"{columns}\n")
# 显示查询结果
for row in results:
tab_query_widgets['result_text'].insert(tk.END, f"{row}\n")
except pymysql.MySQLError as err:
messagebox.showerror("Error", f"Error: {err}")
# 刷新列名和动态生成输入框
def refresh_columns(table_name, tab):
if table_name:
columns = get_columns(table_name)
if 'column_combobox' in tab:
tab['column_combobox']['values'] = columns
if 'dynamic_frame' in tab:
for widget in tab['dynamic_frame'].winfo_children():
widget.destroy()
tab['entry_dict'].clear() # 确保字典是空的
for column in columns:
tk.Label(tab['dynamic_frame'], text=column).pack()
entry = tk.Entry(tab['dynamic_frame'])
entry.pack()
tab['entry_dict'][column] = entry
# 管理员模式功能
def admin_mode():
clear_tabs()
tab_control.add(tab_add, text='增加数据')
tab_control.add(tab_delete, text='删除数据')
tab_control.add(tab_update, text='更新数据')
tab_control.add(tab_query, text='查询数据')
tab_control.pack(expand=1, fill='both')
tab_add_widgets['table_combobox'].bind("<<ComboboxSelected>>",
lambda event: refresh_columns(tab_add_widgets['table_combobox'].get(),
tab_add_widgets))
# 商家模式功能
def merchant_mode(user_id):
clear_tabs()
tab_control.add(tab_add_product, text='增加商品')
tab_control.add(tab_query_own_products, text='管理自己的商品')
tab_control.pack(expand=1, fill='both')
# 动态生成商品信息的输入框
refresh_columns("Product", tab_add_product_widgets)
# 显示当前商家的商品
query_own_products(user_id)
# 修改添加商品按钮确保传递用户ID
tk.Button(tab_add_product, text="增加商品", command=lambda: add_product(user_id)).pack(pady=5)
def query_own_products(user_id):
try:
query = f"""
SELECT p.*
FROM Product_Merchant pm
JOIN Product p ON pm.ProductID = p.ProductID
WHERE pm.MerchantID = {user_id}
"""
print(query) # 打印SQL查询
mycursor.execute(query)
columns = [desc[0] for desc in mycursor.description]
results = mycursor.fetchall()
tab_query_own_products_widgets['result_text'].delete("1.0", tk.END)
tab_query_own_products_widgets['result_text'].insert(tk.END, f"{columns}\n")
for row in results:
tab_query_own_products_widgets['result_text'].insert(tk.END, f"{row}\n")
except pymysql.MySQLError as err:
messagebox.showerror("Error", f"Error: {err}")
# 增加商品功能(商家模式)
def add_product(user_id):
table_name = "Product"
columns = []
values = []
for column, entry in tab_add_product_widgets['entry_dict'].items():
value = entry.get().strip()
if value:
columns.append(column)
values.append(value)
if not columns or not values:
messagebox.showwarning("警告", "请输入至少一个列值")
return
try:
# 插入商品到Product表
query = f"INSERT INTO {table_name} ({', '.join(columns)}) VALUES ({', '.join(['%s'] * len(values))})"
print(query) # 打印SQL查询
mycursor.execute(query, values)
product_id = mycursor.lastrowid
# 插入商品和商家的关联到Product_Merchant表
query = f"INSERT INTO Product_Merchant (ProductID, MerchantID) VALUES (%s, %s)"
mycursor.execute(query, (product_id, user_id))
conn.commit()
messagebox.showinfo("成功", "商品添加成功")
except pymysql.MySQLError as err:
messagebox.showerror("Error", f"Error: {err}")
# 消费者模式功能
def consumer_mode(user_id):
clear_tabs()
tab_control.add(tab_query_products, text='查询商品')
tab_control.add(tab_manage_cart, text='管理购物车')
tab_control.pack(expand=1, fill='both')
# 显示当前消费者的购物车
query_cart(user_id)
# 查询商品功能(消费者模式)
def query_products():
table_name = "Product"
if not table_name:
messagebox.showwarning("警告", "请选择一个表")
return
try:
mycursor.execute(f"SELECT * FROM {table_name}")
columns = [desc[0] for desc in mycursor.description]
results = mycursor.fetchall()
tab_query_products_widgets['result_text'].delete("1.0", tk.END)
tab_query_products_widgets['result_text'].insert(tk.END, f"{columns}\n")
for row in results:
tab_query_products_widgets['result_text'].insert(tk.END, f"{row}\n")
except pymysql.MySQLError as err:
messagebox.showerror("Error", f"Error: {err}")
# 查询购物车功能(消费者模式)
def query_cart(user_id):
table_name = "ShoppingCart"
if not table_name:
messagebox.showwarning("警告", "请选择一个表")
return
try:
query = f"SELECT * FROM {table_name} WHERE UserID = {user_id}"
mycursor.execute(query)
columns = [desc[0] for desc in mycursor.description]
results = mycursor.fetchall()
tab_manage_cart_widgets['result_text'].delete("1.0", tk.END)
tab_manage_cart_widgets['result_text'].insert(tk.END, f"{columns}\n")
for row in results:
tab_manage_cart_widgets['result_text'].insert(tk.END, f"{row}\n")
except pymysql.MySQLError as err:
messagebox.showerror("Error", f"Error: {err}")
# 删除购物车项功能(消费者模式)
def delete_cart_item():
table_name = "ShoppingCart"
condition_value = tab_delete_cart_item_widgets['entry_condition'].get().strip()
if not table_name or not condition_value:
messagebox.showwarning("警告", "请输入条件值")
return
try:
query = f"DELETE FROM {table_name} WHERE {condition_value}"
mycursor.execute(query)
conn.commit()
messagebox.showinfo("成功", "购物车项删除成功")
except pymysql.MySQLError as err:
messagebox.showerror("Error", f"Error: {err}")
# 更新购物车项数量功能(消费者模式)
def update_cart_item_quantity():
table_name = "ShoppingCart"
new_value = tab_update_cart_item_quantity_widgets['entry_update'].get().strip()
condition_value = tab_update_cart_item_quantity_widgets['entry_condition'].get().strip()
if not table_name or not new_value or not condition_value:
messagebox.showwarning("警告", "请输入新值和条件值")
return
try:
query = f"UPDATE {table_name} SET Quantity = {new_value} WHERE {condition_value}"
mycursor.execute(query)
conn.commit()
messagebox.showinfo("成功", "购物车项数量更新成功")
except pymysql.MySQLError as err:
messagebox.showerror("Error", f"Error: {err}")
# 角色选择功能
def role_selection():
selected_role = role_combobox.get()
user_id = user_id_entry.get().strip()
if selected_role == "管理员":
admin_mode()
elif selected_role == "商家":
merchant_mode(user_id)
elif selected_role == "消费者":
consumer_mode(user_id)
# 创建角色选择界面
tk.Label(root, text="选择角色:").pack(pady=5)
role_combobox = ttk.Combobox(root, values=roles)
role_combobox.pack(pady=5)
tk.Label(root, text="用户ID:").pack(pady=5)
user_id_entry = tk.Entry(root)
user_id_entry.pack(pady=5)
tk.Button(root, text="进入", command=role_selection).pack(pady=5)
# 创建Tab控制
tab_control = ttk.Notebook(root)
# 创建增加数据Tab管理员模式
tab_add = ttk.Frame(tab_control)
tab_add_widgets = {
'table_combobox': ttk.Combobox(tab_add, values=tables),
'dynamic_frame': tk.Frame(tab_add),
'entry_dict': {}
}
tk.Label(tab_add, text="选择表:").pack(pady=5)
tab_add_widgets['table_combobox'].pack(pady=5)
tab_add_widgets['table_combobox'].bind("<<ComboboxSelected>>",
lambda event: refresh_columns(tab_add_widgets['table_combobox'].get(),
tab_add_widgets))
tab_add_widgets['dynamic_frame'].pack(pady=5)
tk.Button(tab_add, text="增加数据", command=add_data).pack(pady=5)
# 创建删除数据Tab管理员模式
tab_delete = ttk.Frame(tab_control)
tab_delete_widgets = {
'table_combobox': ttk.Combobox(tab_delete, values=tables),
'entry_condition': tk.Entry(tab_delete)
}
tk.Label(tab_delete, text="选择表:").pack(pady=5)
tab_delete_widgets['table_combobox'].pack(pady=5)
tk.Label(tab_delete, text="输入条件值:").pack(pady=5)
tab_delete_widgets['entry_condition'].pack(pady=5)
tk.Button(tab_delete, text="删除数据", command=delete_data).pack(pady=5)
# 创建更新数据Tab管理员模式
tab_update = ttk.Frame(tab_control)
tab_update_widgets = {
'table_combobox': ttk.Combobox(tab_update, values=tables),
'column_combobox': ttk.Combobox(tab_update),
'entry_update': tk.Entry(tab_update),
'entry_condition': tk.Entry(tab_update)
}
tk.Label(tab_update, text="选择表:").pack(pady=5)
tab_update_widgets['table_combobox'].pack(pady=5)
tab_update_widgets['table_combobox'].bind("<<ComboboxSelected>>",
lambda event: refresh_columns(tab_update_widgets['table_combobox'].get(),
tab_update_widgets))
tk.Label(tab_update, text="选择列:").pack(pady=5)
tab_update_widgets['column_combobox'].pack(pady=5)
tk.Label(tab_update, text="输入新值:").pack(pady=5)
tab_update_widgets['entry_update'].pack(pady=5)
tk.Label(tab_update, text="输入条件值:").pack(pady=5)
tab_update_widgets['entry_condition'].pack(pady=5)
tk.Button(tab_update, text="更新数据", command=update_data).pack(pady=5)
# 创建查询数据Tab管理员模式
tab_query = ttk.Frame(tab_control)
tab_query_widgets = {
'table_combobox': ttk.Combobox(tab_query, values=tables),
'result_text': tk.Text(tab_query, height=10, width=80)
}
tk.Label(tab_query, text="选择表:").pack(pady=5)
tab_query_widgets['table_combobox'].pack(pady=5)
tk.Button(tab_query, text="查询数据", command=execute_query).pack(pady=5)
tab_query_widgets['result_text'].pack(pady=5)
# 创建增加商品Tab商家模式
tab_add_product = ttk.Frame(tab_control)
tab_add_product_widgets = {
'dynamic_frame': tk.Frame(tab_add_product),
'entry_dict': {}
}
tk.Label(tab_add_product, text="输入商品信息:").pack(pady=5)
tab_add_product_widgets['dynamic_frame'].pack(pady=5)
tk.Button(tab_add_product, text="增加商品", command=add_product).pack(pady=5)
# 创建管理自己商品Tab商家模式
tab_query_own_products = ttk.Frame(tab_control)
tab_query_own_products_widgets = {
'result_text': tk.Text(tab_query_own_products, height=10, width=80)
}
tk.Label(tab_query_own_products, text="管理自己的商品:").pack(pady=5)
tab_query_own_products_widgets['result_text'].pack(pady=5)
# 创建查询商品Tab消费者模式
tab_query_products = ttk.Frame(tab_control)
tab_query_products_widgets = {
'result_text': tk.Text(tab_query_products, height=10, width=80)
}
tk.Label(tab_query_products, text="商品信息:").pack(pady=5)
tk.Button(tab_query_products, text="查询商品", command=query_products).pack(pady=5)
tab_query_products_widgets['result_text'].pack(pady=5)
# 增加购物车项功能(消费者模式)
def add_cart_item():
table_name = "ShoppingCart"
columns = []
values = []
for column, entry in tab_add_cart_item_widgets['entry_dict'].items():
value = entry.get().strip()
if value:
columns.append(column)
values.append(value)
if not columns or not values:
messagebox.showwarning("警告", "请输入至少一个列值")
return
try:
query = f"INSERT INTO {table_name} ({', '.join(columns)}) VALUES ({', '.join(['%s'] * len(values))})"
print(query) # 打印SQL查询
mycursor.execute(query, values)
conn.commit()
messagebox.showinfo("成功", "购物车项添加成功")
except pymysql.MySQLError as err:
messagebox.showerror("Error", f"Error: {err}")
# 刷新列名和动态生成输入框
def refresh_cart_columns(table_name, tab):
if table_name:
columns = get_columns(table_name)
if 'dynamic_frame' in tab:
for widget in tab['dynamic_frame'].winfo_children():
widget.destroy()
tab['entry_dict'].clear() # 确保字典是空的
for column in columns:
tk.Label(tab['dynamic_frame'], text=column).pack()
entry = tk.Entry(tab['dynamic_frame'])
entry.pack()
tab['entry_dict'][column] = entry
# 查询数据功能(管理员模式)
def execute_query():
table_name = tab_query_widgets['table_combobox'].get()
condition_value = tab_query_widgets['entry_condition'].get().strip()
if not table_name:
messagebox.showwarning("警告", "请选择一个表")
return
try:
# 构造查询语句,加入条件值(如果有)
if condition_value:
query = f"SELECT * FROM {table_name} WHERE {condition_value}"
else:
query = f"SELECT * FROM {table_name}"
mycursor.execute(query)
columns = [desc[0] for desc in mycursor.description]
results = mycursor.fetchall()
# 清空结果区
tab_query_widgets['result_text'].delete("1.0", tk.END)
# 显示列名
tab_query_widgets['result_text'].insert(tk.END, f"{columns}\n")
# 显示查询结果
for row in results:
tab_query_widgets['result_text'].insert(tk.END, f"{row}\n")
except pymysql.MySQLError as err:
messagebox.showerror("Error", f"Error: {err}")
# 更新查询数据Tab管理员模式增加条件输入框
tab_query = ttk.Frame(tab_control)
tab_query_widgets = {
'table_combobox': ttk.Combobox(tab_query, values=tables),
'entry_condition': tk.Entry(tab_query), # 新增条件输入框
'result_text': tk.Text(tab_query, height=10, width=80)
}
tk.Label(tab_query, text="选择表:").pack(pady=5)
tab_query_widgets['table_combobox'].pack(pady=5)
tk.Label(tab_query, text="输入查询条件 (可选):").pack(pady=5) # 条件标签
tab_query_widgets['entry_condition'].pack(pady=5) # 条件输入框
tk.Button(tab_query, text="查询数据", command=execute_query).pack(pady=5)
tab_query_widgets['result_text'].pack(pady=5)
# 创建管理购物车Tab消费者模式
tab_manage_cart = ttk.Frame(tab_control)
# 添加购物车项
tab_add_cart_item_widgets = {
'dynamic_frame': tk.Frame(tab_manage_cart),
'entry_dict': {}
}
tk.Label(tab_manage_cart, text="添加购物车项:").pack(pady=5)
tab_add_cart_item_widgets['dynamic_frame'].pack(pady=5)
tk.Button(tab_manage_cart, text="添加购物车项", command=add_cart_item).pack(pady=5)
# 动态生成购物车项的输入框
refresh_cart_columns("ShoppingCart", tab_add_cart_item_widgets)
# 删除购物车项
tab_delete_cart_item_widgets = {
'entry_condition': tk.Entry(tab_manage_cart)
}
tk.Label(tab_manage_cart, text="删除购物车项 - 输入条件:").pack(pady=5)
tab_delete_cart_item_widgets['entry_condition'].pack(pady=5)
tk.Button(tab_manage_cart, text="删除购物车项", command=delete_cart_item).pack(pady=5)
# 更新购物车项数量
tab_update_cart_item_quantity_widgets = {
'entry_update': tk.Entry(tab_manage_cart),
'entry_condition': tk.Entry(tab_manage_cart)
}
tk.Label(tab_manage_cart, text="更新购物车项数量:").pack(pady=5)
tk.Label(tab_manage_cart, text="输入新数量:").pack(pady=5)
tab_update_cart_item_quantity_widgets['entry_update'].pack(pady=5)
tk.Label(tab_manage_cart, text="输入条件:").pack(pady=5)
tab_update_cart_item_quantity_widgets['entry_condition'].pack(pady=5)
tk.Button(tab_manage_cart, text="更新数量", command=update_cart_item_quantity).pack(pady=5)
# 显示购物车项
tab_manage_cart_widgets = {
'result_text': tk.Text(tab_manage_cart, height=10, width=80)
}
tk.Label(tab_manage_cart, text="购物车信息:").pack(pady=5)
tab_manage_cart_widgets['result_text'].pack(pady=5)
# 运行Tkinter主循环
root.mainloop()
# 关闭连接
conn.close()

File diff suppressed because it is too large Load Diff
Loading…
Cancel
Save