pip install sqlalchemy
from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker
# 替换为你的数据库连接字符串 DATABASE_URI = 'sqlite:///example.db' engine = create_engine(DATABASE_URI)
Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) age = Column(Integer)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
# 添加记录 new_user = User(name='John Doe', age=30) session.add(new_user) session.commit() # 查询记录 users = session.query(User).all() for user in users: print(user.id, user.name, user.age) # 更新记录 user_to_update = session.query(User).filter_by(name='John Doe').first() user_to_update.age = 31 session.commit() # 删除记录 user_to_delete = session.query(User).filter_by(name='John Doe').first() session.delete(user_to_delete) session.commit() # 关闭会话 session.close()
以上示例展示了如何使用SQLAlchemy ORM框架连接到数据库并执行基本的CRUD操作。你可以根据自己的需求修改数据模型和数据库连接字符串。