Skip to main content

Explain in Detail SQLAlchemy Library in Python

 

SQLAlchemy in Python: A Comprehensive Guide 

SQLAlchemy is a powerful SQL toolkit and Object-Relational Mapper (ORM) for Python. It allows developers to interact with databases in a Pythonic way, abstracting SQL queries while maintaining high performance.


🔹 Why Use SQLAlchemy?

ORM & Core: Supports both ORM (Object-Relational Mapping) and Core (direct SQL queries).
Database Agnostic: Works with PostgreSQL, MySQL, SQLite, Oracle, and others.
High Performance: Optimized SQL execution with lazy loading and connection pooling.
Declarative API: Define database schemas using Python classes.
Asynchronous Support: Works with async databases using asyncio.


🔹 Installing SQLAlchemy

To install SQLAlchemy, run:

pip install sqlalchemy

For MySQL support, install an additional driver:

pip install pymysql

For PostgreSQL, use:

pip install psycopg2

🔹 Connecting to a Database

SQLAlchemy uses connection strings to connect to databases.

from sqlalchemy import create_engine

# SQLite
engine = create_engine("sqlite:///example.db")

# PostgreSQL
# engine = create_engine("postgresql://user:password@localhost/dbname")

# MySQL
# engine = create_engine("mysql+pymysql://user:password@localhost/dbname")

print("Database connected successfully!")

create_engine() creates a connection to the database.


🔹 SQLAlchemy ORM (Object-Relational Mapping)

ORM lets you interact with a database using Python classes instead of raw SQL.


🔹 Defining a Database Model

In SQLAlchemy ORM, you define a model (table structure) using a Python class.

📌 Example: Defining a User Model

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()  # Base class for models

class User(Base):
    __tablename__ = "users"  # Table name in the database
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(50), nullable=False)
    email = Column(String(100), unique=True, nullable=False)

print("User model created!")

📌 Explanation

  • Base = declarative_base(): Creates a base class for all models.
  • __tablename__: Defines the table name.
  • Column(): Defines columns with data types (Integer, String, etc.).
  • primary_key=True: Sets a primary key.
  • nullable=False: Ensures mandatory fields.
  • unique=True: Prevents duplicate values.

🔹 Creating the Database Table

After defining the models, we create the tables in the database.

from sqlalchemy.orm import sessionmaker

# Create the database engine
engine = create_engine("sqlite:///example.db")

# Create all tables
Base.metadata.create_all(engine)

print("Tables created successfully!")

🔹 CRUD Operations in SQLAlchemy

CRUD stands for Create, Read, Update, Delete. SQLAlchemy ORM simplifies these operations.

1️⃣ Creating a Database Session

A session allows us to interact with the database.

Session = sessionmaker(bind=engine)
session = Session()

2️⃣ Creating (Inserting) Data

new_user = User(name="Alice", email="alice@example.com")
session.add(new_user)  # Add to session
session.commit()  # Save to database
print("User added successfully!")

3️⃣ Reading (Fetching) Data

Fetch all users

users = session.query(User).all()
for user in users:
    print(user.id, user.name, user.email)

Fetch a single user by ID

user = session.query(User).filter_by(id=1).first()
print(user.name)

Using filter() for advanced queries

users = session.query(User).filter(User.name.like("%Alice%")).all()

4️⃣ Updating Data

user = session.query(User).filter_by(id=1).first()
user.name = "Alice Johnson"
session.commit()  # Save changes
print("User updated successfully!")

5️⃣ Deleting Data

user = session.query(User).filter_by(id=1).first()
session.delete(user)
session.commit()
print("User deleted successfully!")

🔹 SQLAlchemy Core (Executing Raw SQL Queries)

SQLAlchemy also allows you to write raw SQL queries.

from sqlalchemy import text

with engine.connect() as conn:
    result = conn.execute(text("SELECT * FROM users"))
    for row in result:
        print(row)

🔹 FastAPI + SQLAlchemy Integration

SQLAlchemy is commonly used with FastAPI for building APIs.

📌 Example: FastAPI with SQLAlchemy

from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session
from database import SessionLocal, engine, Base
from models import User

app = FastAPI()

# Dependency to get the database session
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.get("/users/")
async def get_users(db: Session = Depends(get_db)):
    users = db.query(User).all()
    return users

🔹 SQLAlchemy Relationship (One-to-Many, Many-to-Many)

SQLAlchemy supports relationships between tables.

📌 One-to-Many Relationship

Example: A User can have multiple Posts.

from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship

class Post(Base):
    __tablename__ = "posts"
    id = Column(Integer, primary_key=True, autoincrement=True)
    title = Column(String(100), nullable=False)
    content = Column(String(500), nullable=False)
    user_id = Column(Integer, ForeignKey("users.id"))  # Foreign key to users table

    user = relationship("User", back_populates="posts")

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(50), nullable=False)
    email = Column(String(100), unique=True, nullable=False)

    posts = relationship("Post", back_populates="user")

📌 Now, when fetching a user, we can also get their posts.


🔹 SQLAlchemy Async Support

SQLAlchemy supports async queries using asyncio.

📌 Async SQLAlchemy Example

from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine

async_engine = create_async_engine("sqlite+aiosqlite:///example.db")
async_session = AsyncSession(async_engine)

🎯 Conclusion

SQLAlchemy is a powerful ORM & SQL toolkit that simplifies database interactions.

✅ Key Takeaways

  • ORM Models: Define database tables using Python classes.
  • CRUD Operations: Easily create, read, update, and delete records.
  • Relationships: Supports One-to-Many and Many-to-Many relationships.
  • FastAPI Integration: Works seamlessly with FastAPI.
  • Async Support: Supports asyncio for high-performance applications.


Comments

Popular posts from this blog

Simple Linear Regression - and Related Regression Loss Functions

Today's Topics: a. Regression Algorithms  b. Outliers - Explained in Simple Terms c. Common Regression Metrics Explained d. Overfitting and Underfitting e. How are Linear and Non Linear Regression Algorithms used in Neural Networks [Future study topics] Regression Algorithms Regression algorithms are a category of machine learning methods used to predict a continuous numerical value. Linear regression is a simple, powerful, and interpretable algorithm for this type of problem. Quick Example: These are the scores of students vs. the hours they spent studying. Looking at this dataset of student scores and their corresponding study hours, can we determine what score someone might achieve after studying for a random number of hours? Example: From the graph, we can estimate that 4 hours of daily study would result in a score near 80. It is a simple example, but for more complex tasks the underlying concept will be similar. If you understand this graph, you will understand this blog. Sim...

What problems can AI Neural Networks solve

How does AI Neural Networks solve Problems? What problems can AI Neural Networks solve? Based on effectiveness and common usage, here's the ranking from best to least suitable for neural networks (Classification Problems, Regression Problems and Optimization Problems.) But first some Math, background and related topics as how the Neural Network Learn by training (Supervised Learning and Unsupervised Learning.)  Background Note - Mathematical Precision vs. Practical AI Solutions. Math can solve all these problems with very accurate results. While Math can theoretically solve classification, regression, and optimization problems with perfect accuracy, such calculations often require impractical amounts of time—hours, days, or even years for complex real-world scenarios. In practice, we rarely need absolute precision; instead, we need actionable results quickly enough to make timely decisions. Neural networks excel at this trade-off, providing "good enough" solutions in seco...

Activation Functions in Neural Networks

  A Guide to Activation Functions in Neural Networks 🧠 Question: Without activation function can a neural network with many layers be non-linear? Answer: Provided at the end of this document. Activation functions are a crucial component of neural networks. Their primary purpose is to introduce non-linearity , which allows the network to learn the complex, winding patterns found in real-world data. Without them, a neural network, no matter how deep, would just be a simple linear model. In the diagram below the f is the activation function that receives input and send output to next layers. Commonly used activation functions. 1. Sigmoid Function 2. Tanh (Hyperbolic Tangent) 3. ReLU (Rectified Linear Unit - Like an Electronic Diode) 4. Leaky ReLU & PReLU 5. ELU (Exponential Linear Unit) 6. Softmax 7. GELU, Swish, and SiLU 1. Sigmoid Function                       The classic "S-curve," Sigmoid squashes any input value t...