SQLAlchemy Part 02 -Insert data into that table

tech kamar
Jun 26, 2024

Part 01 Link here

Create SessionMaker object

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

Create Object of ORM class

user = User(username="admin", password="pass1234")

Add entry to database and commit db

db_session.add(user)
db_session.commit()

Now lets see the full 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()

# Create object of user class
user = User(username="admin", password="pass1234")

# Insert data into table
db_session.add(user)
db_session.commit()

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