建立一个仓库管理系统的python代码并且与数据库连接
时间: 2024-02-05 12:04:17 浏览: 40
以下是一个使用SQLite数据库与Python连接的仓库管理系统代码示例:
```python
import sqlite3
class Item:
def __init__(self, name, price, quantity):
self.name = name
self.price = price
self.quantity = quantity
class Inventory:
def __init__(self):
self.conn = sqlite3.connect('inventory.db')
self.create_table()
def create_table(self):
c = self.conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS items
(name TEXT, price REAL, quantity INTEGER)''')
self.conn.commit()
def add_item(self, item):
c = self.conn.cursor()
c.execute("INSERT INTO items VALUES (?, ?, ?)", (item.name, item.price, item.quantity))
self.conn.commit()
def remove_item(self, name):
c = self.conn.cursor()
c.execute("DELETE FROM items WHERE name=?", (name,))
self.conn.commit()
def update_item(self, name, price, quantity):
c = self.conn.cursor()
c.execute("UPDATE items SET price=?, quantity=? WHERE name=?", (price, quantity, name))
self.conn.commit()
def display_inventory(self):
c = self.conn.cursor()
c.execute("SELECT * FROM items")
rows = c.fetchall()
for row in rows:
print(f"{row[0]} - Price: {row[1]} - Quantity: {row[2]}")
inventory = Inventory()
while True:
print("1. Add item")
print("2. Remove item")
print("3. Update item")
print("4. Display inventory")
print("5. Exit")
choice = int(input("Enter choice: "))
if choice == 1:
name = input("Enter item name: ")
price = float(input("Enter item price: "))
quantity = int(input("Enter item quantity: "))
item = Item(name, price, quantity)
inventory.add_item(item)
print("Item added.")
elif choice == 2:
name = input("Enter item name: ")
inventory.remove_item(name)
print("Item removed.")
elif choice == 3:
name = input("Enter item name: ")
price = float(input("Enter item price: "))
quantity = int(input("Enter item quantity: "))
inventory.update_item(name, price, quantity)
print("Item updated.")
elif choice == 4:
inventory.display_inventory()
elif choice == 5:
break
else:
print("Invalid choice. Try again.")
```
这个程序与前面的示例非常相似,但使用了SQLite数据库。程序首先创建了一个名为`inventory.db`的数据库文件和一个名为`items`的表。然后,程序将所有的存货项存储在数据库中。用户可以使用数字选择操作。程序还包括一个循环,直到用户选择退出。注意,在每个数据库操作后,程序都会调用`commit()`方法来确保更改已保存到数据库中。