Course contentsShow
← Data Science
Lesson 1119 of 2,14528. Working with Databases from PythonFree lesson

Setting Up SQLAlchemy and Creating an Engine

Installing SQLAlchemy, creating database engines, and establishing connections.

Setting Up SQLAlchemy and Creating an Engine

You'll learn how to install SQLAlchemy and create an engine to connect Python code to databases.

Now that you understand the difference between SQLAlchemy Core and ORM, it's time to get SQLAlchemy running. Think of the SQLAlchemy engine as the power source for all your database operations—it's the bridge that connects your Python code to your database, managing connections behind the scenes.

Installing SQLAlchemy

SQLAlchemy is a third-party package, so you'll need to install it first:

# In your terminal or command prompt
pip install sqlalchemy

You may also want to install database-specific drivers (like psycopg2 for PostgreSQL), but SQLAlchemy includes built-in support for SQLite.

Creating an Engine

The engine is the starting point for any SQLAlchemy application. It's a factory that creates and manages database connections using connection strings (which you learned about earlier):

from sqlalchemy import create_engine

# SQLite example (database file)
engine = create_engine('sqlite:///my_database.db')

# PostgreSQL example (requires psycopg2)
# engine = create_engine('postgresql://user:password@localhost:5432/mydb')

The engine doesn't immediately connect to the database—it waits until you actually need a connection. This "lazy" approach is efficient and follows connection pooling principles you've already seen.

Testing the Connection

You can verify your engine works:

with engine.connect() as connection:
    print("Connection successful!")

The engine handles opening and closing connections automatically when you use context managers, just like the connection management patterns you practiced earlier.

Key Takeaway: SQLAlchemy's engine is installed via pip install sqlalchemy and created with create_engine() using a connection string—it acts as the central connection manager for all database operations.