python 代码 使用pymysql保存数据,实现超市日常管理中以下业务。 一、建立以下数据表并填充数据 产品表:products 列名:id 编号num 名称name 单价price 折扣discount 订单表:orders 列名:id 编号num 货品数量count 金额amount 二、实现以下菜单并实现业务: 6.查看所有订单; 7.订单统计(显示总销售额和货品数量); 8.商品结算
时间: 2024-04-11 13:28:20 浏览: 8
您好!以下是使用pymysql保存数据并实现超市日常管理中的业务的 Python 代码示例:
```python
import pymysql
# 连接数据库
conn = pymysql.connect(host='localhost', user='root', password='your_password', database='your_database')
cursor = conn.cursor()
# 创建产品表
create_products_table = '''
CREATE TABLE IF NOT EXISTS products (
id INT PRIMARY KEY AUTO_INCREMENT,
num VARCHAR(50),
name VARCHAR(100),
price FLOAT,
discount FLOAT
)
'''
cursor.execute(create_products_table)
# 创建订单表
create_orders_table = '''
CREATE TABLE IF NOT EXISTS orders (
id INT PRIMARY KEY AUTO_INCREMENT,
num VARCHAR(50),
count INT,
amount FLOAT
)
'''
cursor.execute(create_orders_table)
# 填充产品数据
insert_products_data = '''
INSERT INTO products (num, name, price, discount) VALUES
('P001', 'Product 1', 10.0, 0.1),
('P002', 'Product 2', 20.0, 0.2),
('P003', 'Product 3', 30.0, 0.3)
'''
cursor.execute(insert_products_data)
# 菜单实现
def show_all_orders():
# 查询所有订单
select_all_orders = '''
SELECT * FROM orders
'''
cursor.execute(select_all_orders)
orders = cursor.fetchall()
# 打印订单信息
for order in orders:
print(f"订单编号: {order[1]}, 货品数量: {order[2]}, 金额: {order[3]}")
def order_statistics():
# 订单统计
select_order_statistics = '''
SELECT SUM(count) AS total_count, SUM(amount) AS total_amount FROM orders
'''
cursor.execute(select_order_statistics)
statistics = cursor.fetchone()
# 打印统计结果
print(f"总销售额: {statistics[1]}, 货品数量: {statistics[0]}")
def calculate_product():
product_num = input("请输入产品编号: ")
product_count = int(input("请输入购买数量: "))
# 查询产品信息
select_product = '''
SELECT price, discount FROM products WHERE num=%s
'''
cursor.execute(select_product, (product_num,))
product = cursor.fetchone()
if product:
price = product[0]
discount = product[1]
# 计算金额
amount = price * product_count * (1 - discount)
# 插入订单数据
insert_order = '''
INSERT INTO orders (num, count, amount) VALUES (%s, %s, %s)
'''
cursor.execute(insert_order, (product_num, product_count, amount))
conn.commit()
print(f"订单已生成,金额为: {amount}")
else:
print("产品不存在")
# 菜单选项
while True:
print("------ 超市日常管理 ------")
print("1. 查看所有订单")
print("2. 订单统计")
print("3. 商品结算")
print("0. 退出")
choice = int(input("请输入选项: "))
if choice == 1:
show_all_orders()
elif choice == 2:
order_statistics()
elif choice == 3:
calculate_product()
elif choice == 0:
break
else:
print("无效的选项")
# 关闭数据库连接
cursor.close()
conn.close()
```
请将 `your_password` 替换为您的数据库密码,`your_database` 替换为您的数据库名称。此代码实现了菜单选项:查看所有订单、订单统计和商品结算。您可以根据需要进行调整和扩展。