写一个商品管理系统个代码
时间: 2023-12-13 20:03:58 浏览: 31
好的,这里是一个简单的商品管理系统的代码示例(使用Python语言和SQLite数据库):
```python
import sqlite3
# 连接数据库
conn = sqlite3.connect('products.db')
c = conn.cursor()
# 创建商品表格
c.execute('''CREATE TABLE IF NOT EXISTS products
(id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
price REAL NOT NULL,
quantity INTEGER NOT NULL)''')
# 添加商品
def add_product(name, price, quantity):
c.execute("INSERT INTO products (name, price, quantity) VALUES (?, ?, ?)", (name, price, quantity))
conn.commit()
print("商品添加成功!")
# 删除商品
def delete_product(id):
c.execute("DELETE FROM products WHERE id=?", (id,))
conn.commit()
print("商品删除成功!")
# 更新商品数量
def update_product_quantity(id, quantity):
c.execute("UPDATE products SET quantity=? WHERE id=?", (quantity, id))
conn.commit()
print("商品数量更新成功!")
# 查询所有商品
def get_all_products():
c.execute("SELECT * FROM products")
rows = c.fetchall()
if len(rows) == 0:
print("没有任何商品!")
else:
for row in rows:
print(f"{row[0]}. {row[1]}, 价格:{row[2]}, 数量:{row[3]}")
# 根据ID查询商品
def get_product_by_id(id):
c.execute("SELECT * FROM products WHERE id=?", (id,))
row = c.fetchone()
if row is None:
print("没有找到该商品!")
else:
print(f"{row[0]}. {row[1]}, 价格:{row[2]}, 数量:{row[3]}")
# 关闭数据库连接
def close_connection():
conn.close()
print("数据库连接已关闭!")
# 菜单
while True:
print("\n请选择操作:")
print("1. 添加商品")
print("2. 删除商品")
print("3. 更新商品数量")
print("4. 查询所有商品")
print("5. 根据ID查询商品")
print("6. 退出")
choice = input()
if choice == '1':
name = input("请输入商品名称:")
price = float(input("请输入商品价格:"))
quantity = int(input("请输入商品数量:"))
add_product(name, price, quantity)
elif choice == '2':
id = int(input("请输入要删除的商品ID:"))
delete_product(id)
elif choice == '3':
id = int(input("请输入要更新数量的商品ID:"))
quantity = int(input("请输入新的商品数量:"))
update_product_quantity(id, quantity)
elif choice == '4':
get_all_products()
elif choice == '5':
id = int(input("请输入要查询的商品ID:"))
get_product_by_id(id)
elif choice == '6':
close_connection()
break
else:
print("无效的选择,请重新输入!")
```
这个示例代码实现了添加、删除、更新、查询商品等基本功能,你可以根据自己的需求进行修改和扩展。