SQLAlchemy中sessionmaker调用add_all/commit报AttributeError问题求助
问题分析与解决
核心错误原因
你犯了初学者常见的错误:sessionmaker 是会话工厂类,不是直接可用的会话对象。你把 session 赋值成了 Session 这个类本身,而非调用它创建实例,所以才会出现“没有add_all、commit属性”的报错——这些都是会话实例的方法,不是类的方法。
具体修正步骤
1. 修复会话创建代码
把原来的:
session = Session
改成:
session = Session() # 调用工厂类创建真正的会话实例
2. 补充add_all()的参数
add_all() 必须接收一个包含模型实例的可迭代对象(比如列表),你当前没传参数,会触发新错误。修改为:
session.add_all([student1, student2, student3, student4, student5])
3. 确保表已创建(可选)
如果是第一次运行代码,需要取消 Base.metadata.create_all(engine) 的注释,先在数据库中创建student表;后续重复运行时可以再注释掉,避免重复执行建表操作。
完整修正后的代码
# import libraries from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.orm import declarative_base from sqlalchemy.orm import sessionmaker import psycopg2 # creating the engine engine = create_engine('postgresql://postgres:password123@localhost:5432/alchemy', echo=False) # creating the session Session = sessionmaker(bind=engine) session = Session() # 修正:创建会话实例 # creating the table Base = declarative_base() # creating the class that inherit the base class Student(Base): __tablename__ = "student" id = Column(Integer, primary_key=True) name = Column(String(50)) age = Column(Integer) grade = Column(String) # migrating table to database Base.metadata.create_all(engine) # 第一次运行取消注释,建表后可注释 # create instance of table class student1 = Student(name="mike", age=32, grade="second") student2 = Student(name="jenn", age=31, grade="first") student3 = Student(name="joe", age=23, grade="third") student4 = Student(name="jack", age=26, grade="forth") student5 = Student(name="rose", age=28, grade="fifth") # add data to the session we created before session.add_all([student1, student2, student3, student4, student5]) # 修正:传入实例列表 session.commit() session.close() # 建议执行完操作后关闭会话
额外提示
- SQLAlchemy 2.x版本中,
declarative_base()仍可正常使用,但官方推荐更现代的DeclarativeBase类,你后续深入学习时可以了解。 - 记得在操作完成后关闭会话,避免数据库连接泄漏。
内容的提问来源于stack exchange,提问作者zorg
相关产品推荐
相关产品推荐

