
![]() |
@wtf | |
SQLAlchemy Database Toolkit & ORM |
||
1
Replies
17
Views
1 Bookmarks
|
![]() |
@wtf | 8 August 25 |
SQLAlchemy is a powerful Python SQL toolkit and Object-Relational Mapper (ORM) that gives developers full control over SQL and database interactions with both high-level and low-level access. Why Use SQLAlchemy? Works with multiple databases (SQLite, MySQL, PostgreSQL, etc.) Clean separation between schema and business logic ORM + Core (SQL Expression Language) Helps avoid raw SQL and SQL injection risks Flexible, scalable, and production-ready Installation bash pip install SQLAlchemy Basic Setup python from sqlalchemy import create_engine engine = create_engine('sqlite:///example.db', echo=True) Defining Models (ORM) python from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class User(Base): _tablename_ = 'users' id = Column(Integer, primary_key=True) name = Column(String) age = Column(Integer) Creating Tables python Base.metadata.create_all(engine) Working with Sessions python from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind=engine) session = Session() new_user = User(name=Alice, age=25) session.add(new_user) session.commit() Querying Data python users = session.query(User).filter_by(name=Alice).all() for user in users: print(user.name, user.age) Real-World Use Cases Backend of web apps (Flask, FastAPI, Django) Scalable enterprise apps Data migration & analytics tools Database-heavy services Summary Ideal For: Developers needing robust database interaction Strength: Flexible ORM & raw SQL support Bonus: Works well with frameworks like Flask and FastAPI |
||


