SQLAlchemy Part 03 -Read all data from table

tech kamar
Jun 26, 2024

Part 02 Link here

Retrieve all entries from table and print

user_list = db_session.query(User).all()
print("Data in User Table...")
for curr_user in user_list:
print("\nId = "+str(curr_user.id))
print("Username = "+str(curr_user.username))
print("Password = "+str(curr_user.password))

Now lets see the entire code…

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()

# Create ORM Class for User
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, autoincrement=True)
username = Column(String(255),unique=True, nullable=False)
password = Column(String(255),nullable=False)

# Create Engine
SQLALCHEMY_DATABASE_URL = "postgresql://admin:dbpass@localhost:5432/mydb"
engine = create_engine(SQLALCHEMY_DATABASE_URL,pool_size=5,pool_recycle=1800,pool_pre_ping=True)

# Create Session
local_session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
db_session = local_session()

# Retrieve and print all the data
user_list = db_session.query(User).all()
print("Data in User Table...")
for curr_user in user_list:
print("\nId = "+str(curr_user.id))
print("Username = "+str(curr_user.username))
print("Password = "+str(curr_user.password))

Part 04 Link here

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response