parent
1b778dbb7b
commit
3e0c393322
@ -0,0 +1,58 @@
|
||||
from sqlalchemy import create_engine, Column, Integer, String
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
# 数据库连接配置
|
||||
DATABASE_URI = 'sqlite:///hotel_rooms.db'
|
||||
engine = create_engine(DATABASE_URI)
|
||||
Base = declarative_base()
|
||||
Session = sessionmaker(bind=engine)
|
||||
session = Session()
|
||||
|
||||
# Room模型定义
|
||||
class Room(Base):
|
||||
__tablename__ = 'rooms'
|
||||
id = Column(Integer, primary_key=True)
|
||||
room_number = Column(Integer, unique=True, nullable=False)
|
||||
room_type = Column(String, nullable=False) # 如 'single', 'double', 'suite'
|
||||
status = Column(String, nullable=False, default='available') # 如 'available', 'occupied', 'maintenance'
|
||||
|
||||
def __repr__(self):
|
||||
return f"Room(number={self.room_number}, type='{self.room_type}', status='{self.status}')"
|
||||
|
||||
# 数据库表结构创建
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
def add_room(room_number, room_type):
|
||||
"""添加房间到数据库"""
|
||||
if session.query(Room).filter_by(room_number=room_number).first():
|
||||
return "该房间号已存在,请选择其他房间号。"
|
||||
new_room = Room(room_number=room_number, room_type=room_type)
|
||||
session.add(new_room)
|
||||
session.commit()
|
||||
return f"房间号为{room_number}的{room_type}型房间已添加。"
|
||||
|
||||
def list_rooms(status=None):
|
||||
"""查询并列出所有房间,可选指定房间状态"""
|
||||
query = session.query(Room)
|
||||
if status:
|
||||
query = query.filter_by(status=status)
|
||||
return query.all()
|
||||
|
||||
def update_room_status(room_number, new_status):
|
||||
"""更新房间状态"""
|
||||
room = session.query(Room).filter_by(room_number=room_number).first()
|
||||
if not room:
|
||||
return f"未找到房间号为{room_number}的房间。"
|
||||
room.status = new_status
|
||||
session.commit()
|
||||
return f"房间号{room_number}的状态已更新为'{new_status}'。"
|
||||
|
||||
def delete_room(room_number):
|
||||
"""删除指定房间"""
|
||||
room = session.query(Room).filter_by(room_number=room_number).first()
|
||||
if not room:
|
||||
return f"未找到房间号为{room_number}的房间。"
|
||||
session.delete(room)
|
||||
session.commit()
|
||||
return f"房间号为{room_number}的房间已删除。"
|
Loading…
Reference in new issue