
For those getting started with SQLAlchemy, an SQLAlchemy Beginner Guide can be highly beneficial. You know how to use Django Models to talk to a database. But what if you are building a simple desktop app, a data science script, or a Discord bot? You don’t want to install all of Django just for that.
Enter SQLAlchemy. It’s Python’s standalone ORM (Object Relational Mapper). It lets you use Python classes to interact with almost any database (SQLite, PostgreSQL, MySQL).
Step 1: Installation
pip install sqlalchemyStep 2: Define Your Model (The Setup)
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import declarative_base, sessionmaker
# 1. Connect to a simple file-based SQLite database
engine = create_engine('sqlite:///my_database.db')
Base = declarative_base()
# 2. Define the User table as a Python class
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
# 3. Create the table in the database
Base.metadata.create_all(engine)Step 3: Adding Data (The Session)
To talk to the database, we need a “Session”.
Session = sessionmaker(bind=engine)
session = Session()
# Create a new user object
new_user = User(name="Alice", age=30)
# Add and commit (save) it to the database
session.add(new_user)
session.commit()Step 4: Querying Data
# Find all users
all_users = session.query(User).all()
for user in all_users:
print(f"{user.name} is {user.age} years old.")SQLAlchemy is incredibly powerful. This is just the tip of the iceberg!





