SQLAlchemy Part 01 -Create Table from scratch

tech kamar
Jun 26, 2024

Create Table Object. In our case we create a table to store user data

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
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 an Engine to Connect

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 the table in database

Base.metadata.create_all(engine)

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

# Reflect and create table in database
Base.metadata.create_all(engine)

Part 02 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