生成一个简单的出入库系统的代码
时间: 2023-08-04 20:03:28 浏览: 182
以下是一个使用 Python 实现的简单出入库系统代码,仅供参考:
```python
import sqlite3
# 连接数据库
conn = sqlite3.connect('inventory.db')
c = conn.cursor()
# 创建库存表和出入库记录表
c.execute('''CREATE TABLE IF NOT EXISTS inventory
(id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
quantity INTEGER NOT NULL,
unit TEXT NOT NULL)''')
c.execute('''CREATE TABLE IF NOT EXISTS inventory_log
(id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
quantity INTEGER NOT NULL,
type TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''')
# 出库函数
def out(name, quantity):
# 查询库存数量
c.execute("SELECT quantity FROM inventory WHERE name=?", (name,))
result = c.fetchone()
if result is None:
print('物品不存在')
return
else:
current_quantity = result[0]
if current_quantity < quantity:
print('库存不足')
return
else:
# 更新库存数量
c.execute("UPDATE inventory SET quantity=? WHERE name=?", (current_quantity - quantity, name))
conn.commit()
# 添加出库记录
c.execute("INSERT INTO inventory_log (name, quantity, type) VALUES (?, ?, ?)", (name, quantity, '出库'))
conn.commit()
print('出库成功')
# 入库函数
def in_(name, quantity):
# 查询库存数量
c.execute("SELECT quantity FROM inventory WHERE name=?", (name,))
result = c.fetchone()
if result is None:
# 添加新物品
c.execute("INSERT INTO inventory (name, quantity, unit) VALUES (?, ?, ?)", (name, quantity, '个'))
conn.commit()
else:
# 更新库存数量
current_quantity = result[0]
c.execute("UPDATE inventory SET quantity=? WHERE name=?", (current_quantity + quantity, name))
conn.commit()
# 添加入库记录
c.execute("INSERT INTO inventory_log (name, quantity, type) VALUES (?, ?, ?)", (name, quantity, '入库'))
conn.commit()
print('入库成功')
# 查询库存记录函数
def show_inventory():
c.execute("SELECT * FROM inventory")
result = c.fetchall()
if result:
for row in result:
print(row[0], row[1], row[2], row[3])
else:
print('库存为空')
# 查询历史库存信息函数
def show_history(name):
c.execute("SELECT * FROM inventory_log WHERE name=?", (name,))
result = c.fetchall()
if result:
for row in result:
print(row[0], row[1], row[2], row[3], row[4])
else:
print('该物品没有历史记录')
# 菜单函数
def menu():
while True:
print('请选择操作:')
print('1. 出库')
print('2. 入库')
print('3. 查询库存记录')
print('4. 查询历史库存信息')
print('0. 退出')
choice = input()
if choice == '1':
name = input('请输入物品名称:')
quantity = int(input('请输入出库数量:'))
out(name, quantity)
elif choice == '2':
name = input('请输入物品名称:')
quantity = int(input('请输入入库数量:'))
in_(name, quantity)
elif choice == '3':
show_inventory()
elif choice == '4':
name = input('请输入物品名称:')
show_history(name)
elif choice == '0':
break
else:
print('无效操作')
# 运行菜单函数
menu()
# 关闭数据库连接
conn.close()
```
这个代码实现了出库、入库、查询库存记录和查询历史库存信息等操作,使用 SQLite3 作为数据库。在实际应用中,还需要根据需求进行修改和完善。
阅读全文