SQLAlchemy: How to Connect to MySQL Database

Updated: January 4, 2024 By: Guest Contributor Post a comment

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.