Learn the most popular Python ORM by building a complete database application with SQLAlchemy. Master model definitions, database sessions, CRUD operations, and query building. Essential skills for any data engineer working with relational databases in Python.
This document explains the SQLAlchemy ORM example provided in sqlalchemy_example.py.
The example demonstrates how to:
import os from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker db_file = "sqlalchemy_example.db" if os.path.exists(db_file): os.remove(db_file)
This section imports necessary modules and sets up the SQLite database file. If the file already exists, it's removed to start fresh.
Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) username = Column(String(50), unique=True, nullable=False) email = Column(String(120), unique=True, nullable=False) def __repr__(self): return f"<User(username='{self.username}', email='{self.email}')>"
Here, we define the User model. It has three fields: id, username, and email. The repr method provides a string representation of the object.
engine = create_engine(f'sqlite:///{db_file}') Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session()
This code creates the database engine, creates all tables defined in our models, and sets up a session to interact with the database.
try: new_user = User(username='john_doe', email='john@example.com') session.add(new_user) session.commit() user = session.query(User).filter_by(username='john_doe').first() print(f"User: {user.username}, Email: {user.email}") except Exception as e: print(f"An error occurred: {e}") finally: session.close()
This section demonstrates creating a new user (Create operation) and then retrieving that user from the database (Read operation). Error handling is included, and the session is closed in the finally block to ensure proper resource management. Running the Example To run this example:
Ensure you have SQLAlchemy installed:
pip install sqlalchemy
Run the script:
python sqlalchemy_example.py
The script will create a SQLite database file, add a user to it, and then retrieve and print the user's information.