Introduction to SQLAlchemy
What is SQLAlchemy?
SQLAlchemy is a powerful Python library that allows developers to interact with databases using Python code instead of writing raw SQL queries.
It provides two main approaches:
- ORM (Object Relational Mapping) → Work with Python classes
- Core (SQL Expression Language) → Write SQL-like queries in Python
Why SQLAlchemy is So Popular
Here’s why developers love SQLAlchemy:
- Works with multiple databases (MySQL, PostgreSQL, SQLite)
- Reduces boilerplate SQL code
- Flexible (ORM + raw SQL support)
- Production-ready and scalable
- Used in frameworks like FastAPI
SQLAlchemy Architecture (Simple Explanation)
Application (Python Code)↓SQLAlchemy ORM/Core↓Database (SQLite/MySQL/PostgreSQL)
Installation
pip install sqlalchemyYour First SQLAlchemy Program
from sqlalchemy import create_engine# Create database engineengine = create_engine('sqlite:///example.db')# Connect to databaseconnection = engine.connect()# Execute SQLresult = connection.execute("SELECT 'Hello, SQLAlchemy!'")for row in result:print(row)Output:
Hello, SQLAlchemy!
Key Concepts You Must Know
1. Engine
- The entry point to the database
- Manages connections
engine = create_engine('sqlite:///example.db')
2. Connection
- Used to execute raw SQL
conn = engine.connect()
ORM vs Core
| Feature | ORM | Core |
|---|---|---|
| Syntax | Python classes | SQL-like |
| Use Case | App development | Complex queries |
| Learning curve | Easy | Moderate |
Real-World Use Case
Imagine building:
- E-commerce app
- Blog system
- Banking system
Instead of writing:
INSERT INTO users (name, email) VALUES ('John', 'john@example.com');
You write:
user = User(name="John", email="john@example.com")session.add(user)
Common Beginner Mistakes
- Confusing Engine with Session
- Forgetting to commit transactions
- Mixing ORM and raw SQL incorrectly
Comments
Post a Comment