You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
2.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import mysql.connector
from mysql.connector import Error
class Warehouse:
def __init__(self):
self.conn = self.create_connection()
self.cursor = self.conn.cursor()
self.create_table_if_not_exists()
def create_connection(self):
"""创建数据库连接"""
try:
connection = mysql.connector.connect(
host='your_host', # 替换为你的数据库主机名
database='inventory_db', # 使用之前创建的数据库名
user='your_user', # 替换为你的数据库用户名
password='your_password' # 替换为你的数据库密码
)
print("成功连接到MySQL数据库")
return connection
except Error as e:
print(f"连接失败: {e}")
return None
def create_table_if_not_exists(self):
"""如果表不存在,则创建表"""
query = """
CREATE TABLE IF NOT EXISTS items (
id INT AUTO_INCREMENT PRIMARY KEY,
item_name VARCHAR(255) NOT NULL,
quantity INT NOT NULL
)
"""
try:
self.cursor.execute(query)
self.conn.commit()
print("items表已存在或已成功创建")
except Error as e:
print(f"创建表时出错: {e}")
# ...保留原有的add_item, remove_item等方法逻辑但内部实现改为使用SQL操作
def add_item_to_db(self, item_name, quantity):
"""向数据库添加商品"""
query = "INSERT INTO items (item_name, quantity) VALUES (%s, %s)"
values = (item_name, quantity)
try:
self.cursor.execute(query, values)
self.conn.commit()
print(f"已添加 {quantity}{item_name} 到数据库。")
except Error as e:
print(f"插入数据时出错: {e}")
# ...类似地修改remove_item, update_stock, check_stock等方法以使用SQL查询和操作
def close_connection(self):
"""关闭数据库连接"""
if self.conn.is_connected():
self.cursor.close()
self.conn.close()
print("MySQL连接已关闭")
# 记得在程序结束时调用close_connection来关闭数据库连接。