im new in python and still learning this is my code :
# 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 os 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
"""the 'Base.metadata.create_all(engine)' line will transfer to comment after this part because we dont need migrate
in this execution"""
session.add_all()
session.commit()
after running the code i constantly getting this error
line 45, in session.add_all() AttributeError: 'sessionmaker' object has no attribute 'add_all'
same error comes for method 'commit()' too
im using pycharm all module and IDE is updated , a light bulb appear near the line and ask for adding this method to the library sqlalcheamy (2.0.17) python 3.11
i have checked some other stackoverflow questions, they usually used flask which i dont know what is it , im stil trying to learn sqlalchemy
session = Session()
You're missing the parentheses. A call to sessionmaker
returns a Session
object.
Also, use a context manager:
with Session() as session:
session.add(some_object)
session.add(some_other_object)
session.commit()
For more information, check the documentation: Using a sessionmaker