Sling Academy
Home/SQLAlchemy/SQLAlchemy: How to Connect to MySQL Database

SQLAlchemy: How to Connect to MySQL Database

Last updated: January 04, 2024

Overview

SQLAlchemy provides a powerful interface for relational database operations. This guide offers a step-by-step tutorial for connecting to a MySQL database using SQLAlchemy, moving from basic to advanced examples.

Prerequisites

Before we begin, you’ll need to have the following installed:

  • MySQL server
  • SQLAlchemy library
  • MySQL connector for Python, such as mysqlclient or PyMySQL

You can install SQLAlchemy and the MySQL connection driver using pip:

pip install sqlalchemy
pip install mysqlclient  # Or use pymysql

Basic Connection Setup

To start, you’ll need to import the necessary components from SQLAlchemy and establish a connection:

from sqlalchemy import create_engine

# Replace USERNAME, PASSWORD, HOST, PORT, and DBNAME with your credentials
engine = create_engine('mysql+pymysql://USERNAME:PASSWORD@HOST:PORT/DBNAME')

With an engine created, you can now execute queries and interact with your MySQL database.

Creating a Session

To work with the ORM functionality of SQLAlchemy, you need to create a Session:

from sqlalchemy.orm import sessionmaker

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

The session object is now your point of interaction with the database for ORM operations.

Defining Models

SQLAlchemy works with a data model definition to map classes to database tables:

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

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    birthday = Column(Date)

Base.metadata.create_all(engine)

This model allows SQLAlchemy to understand your database schema through Python classes.

Performing Queries

To retrieve data from your database, you can use the session object to perform queries. For example:

users = session.query(User).filter_by(name='John Doe').all()
for user in users:
    print(user.id, user.name, user.birthday)

Queries in SQLAlchemy resemble natural Pythonic expressions for ease of use.

Inserting Data

Adding new records is as simple as creating instances of your models and adding them to a session:

new_user = User(name='Jane Smith', birthday='1990-05-01')
session.add(new_user)
session.commit()

A commit will persist your changes to the database.

Advanced Configurations

You can fine-tune the behavior of SQLAlchemy by using a URL string with additional query parameters for things like pool sizes or timeouts:

engine = create_engine('mysql+pymysql://USERNAME:PASSWORD@HOST:PORT/DBNAME?charset=utf8mb4&pool_pre_ping=True')

This string instructs SQLAlchemy to use a specific character set and pre-ping the connection to handle stale connections gracefully.

Conclusion

This tutorial provided a comprehensive start-to-finish guide on connecting to a MySQL database using SQLAlchemy. By progressing from basic connections to advanced configurations, we’ve unlocked the power of efficient database management through Python code. Whether you’re building small applications or complex systems, SQLAlchemy stands as a robust tool to streamline your database interactions.

Next Article: SQLAlchemy: How to Connect to Multiple Databases Concurrently

Previous Article: SQLAlchemy: 3 Ways to Connect to PostgreSQL Database

Series: SQLAlchemy Tutorials: From Basic to Advanced

SQLAlchemy

You May Also Like

  • SQLAlchemy: Counting rows for each category (2 approaches)
  • SQLAlchemy: Adding a calculated column to SELECT query
  • SQLAlchemy: Grouping data on multiple columns
  • SQLAlchemy: How to temporarily delete a row
  • SQLAlchemy Composite Indexes: The Complete Guide
  • Full-Text Search in SQLAlchemy: The Ultimate Guide
  • SQLAlchemy: What if you don’t close database connections?
  • SQLAlchemy: How to Remove FOREIGN KEY Constraints (2 Ways)
  • SQLAlchemy: How to Create and Use Temporary Tables
  • SQLAlchemy: Saving Categories and Subcategories in the Same Table
  • SQLAlchemy: How to Automatically Delete Old Records
  • Weighted Random Selection in SQLAlchemy: An In-Depth Guide
  • SQLAlchemy: created_at and updated_at columns
  • How to Use Regular Expressions in SQLAlchemy
  • SQLAlchemy: Ways to Find Results by a Keyword
  • SQLAlchemy: How to Bulk Insert Data into a Table
  • SQLAlchemy: How to Update a Record by ID
  • SQLAlchemy: Singular vs Plural Table Names
  • SQLAlchemy: How to Add/Remove a Primary Key Constraint