Skip to content
Permalink
main
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
from sqlalchemy.orm.exc import NoResultFound
from typing import Optional
# 添加产品到数据库
def add_product(name: str, quantity: int, price: float):
"""
向数据库中添加一个新的产品。
:param name: 产品名称
:param quantity: 产品数量
:param price: 产品价格
"""
with Session() as session:
new_product = Product(name=name, quantity=quantity, price=price)
session.add(new_product)
session.commit()
# 根据ID删除产品
def delete_product(product_id: int):
"""
从数据库中删除一个产品。
:param product_id: 要删除的产品的ID
"""
with Session() as session:
product = session.query(Product).get(product_id)
if product:
session.delete(product)
session.commit()
else:
raise NoResultFound(f"Product with ID {product_id} not found.")
# 更新产品信息
def update_product(product_id: int, name: Optional[str] = None, quantity: Optional[int] = None, price: Optional[float] = None):
"""
更新数据库中一个产品的信息。
:param product_id: 要更新的产品的ID
:param name: 新的产品名称(如果提供)
:param quantity: 新的产品数量(如果提供)
:param price: 新的产品价格(如果提供)
"""
with Session() as session:
product = session.query(Product).get(product_id)
if product:
if name:
product.name = name
if quantity:
product.quantity = quantity
if price:
product.price = price
session.commit()
else:
raise NoResultFound(f"Product with ID {product_id} not found.")
# 获取所有产品信息
def get_all_products():
"""
获取数据库中所有产品的列表。
"""
with Session() as session:
return session.query(Product).all()