CodeBlanks Logo Icon CodeBlanks

Engine

Learn the database engine with create_engine.

Engine

create_engine sets up SQLAlchemy's database connection. It takes a connection string and returns an Engine object. For an in-memory SQLite database, use sqlite:///:memory:.

from sqlalchemy import create_engine

engine = create_engine("sqlite:///:memory:")
print(engine.url)

The Engine manages the connection pool; actual queries go through a Session. You create the Engine once in an application.

Connection string

The connection string specifies the database type and location. For SQLite, the form sqlite:///path is used; :memory: means an in-memory database.

# In-memory
engine = create_engine("sqlite:///:memory:")
# File-based
engine = create_engine("sqlite:///uyeler.db")

For other databases, a string like postgresql://user:pass@host/db is used. SQLAlchemy picks the right driver from the string.

Practice Create Engine and print

Start with from sqlalchemy import create_engine. Define an engine with create_engine("sqlite:///:memory:"). Print the connection string with print(engine.url).

Starter code

main.py
# bring in create_engine from sqlalchemy
# define an engine with the in-memory sqlite string
# print the engine's url

Sample solution

main.py
from sqlalchemy import create_engine

engine = create_engine("sqlite:///:memory:")
print(engine.url)

Expected output

sqlite:///:memory:

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What parameter does create_engine use to connect?

  • A file object
  • A connection string Correct answer
  • A class name
  • A user name

Explanation: create_engine takes a connection string to connect to the database.

2 Complete the create_engine call

Question
from sqlalchemy import create_engine

engine = create_engine("____")
Answer
from sqlalchemy import create_engine

engine = create_engine("sqlite:///:memory:")

Explanation: sqlite:///:memory: is an in-memory SQLite database.

3 Match the Engine concepts

Term Meaning
create_engine Creates the engine
engine.url Gives the connection string
sqlite:///:memory: In-memory database
Engine Manages the pool

All lessons in Advanced