Python Tutorial: SQLAlchemy

beginner
9 min

Python Tutorial: SQLAlchemy

Welcome to our comprehensive guide on SQLAlchemy, a powerful and versatile SQL toolkit for Python! Let's embark on this exciting journey together, regardless of your programming level.

What is SQLAlchemy? 🎯

SQLAlchemy is a Python SQL toolkit and Object-Relational Mapping (ORM) system that provides a framework for database access, database schema design, and database ORM. It simplifies the process of working with databases in Python applications, making it a popular choice for developers.

Why Use SQLAlchemy? 💡

  • Simplifies Database Access: SQLAlchemy abstracts away the low-level details of database access, making it easier to work with databases.
  • ORM Support: SQLAlchemy's ORM functionality lets you work with databases using Python objects, making your code cleaner and more Pythonic.
  • Flexibility: SQLAlchemy supports multiple database backends, including MySQL, PostgreSQL, SQLite, and more.

Installation 📝

To install SQLAlchemy, use the following command:

bash
pip install sqlalchemy

Basic Usage 🎯

Connecting to a Database 📝

python
from sqlalchemy import create_engine # Create an engine that connects to a SQLite database (:memory: creates an in-memory database) engine = create_engine('sqlite:///:memory:')

Creating a Table 📝

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)

Adding Rows to a Table 📝

python
from sqlalchemy.orm import sessionmaker DBSession = sessionmaker(bind=engine) session = DBSession() # Add a new user new_user = User(name='John Doe') session.add(new_user) session.commit()

Fetching Data 📝

python
# Fetch all users users = session.query(User).all() for user in users: print(user.name)

Advanced Examples 🎯

Relationships between Tables 📝

python
from sqlalchemy.orm import relationship class Post(Base): __tablename__ = 'posts' id = Column(Integer, primary_key=True) title = Column(String) user_id = Column(Integer, ForeignKey('users.id')) user = relationship("User") class User(Base): # ... (same as before) posts = relationship("Post", back_populates="user")

Working with Multiple Databases 📝

python
# Create a second engine for a MySQL database mysql_engine = create_engine('mysql+pymysql://username:password@localhost/dbname') # Now you can use both engines interchangeably

Quiz 🎯

Quick Quiz
Question 1 of 1

What is SQLAlchemy in Python?