Reading preferences
Concept

SQLAlchemy and Database Boundaries

Follow a transaction while keeping data access separate from the static site.

python, sqlalchemy, databases, transactions, sql

A transaction groups a change

An application can use SQLAlchemy to work with database connections and queries. A transaction groups operations: commit makes changes durable according to the database's guarantees; rollback abandons uncommitted changes. The example below is a separate, temporary in-memory SQLite database, not an Intuvo service.

Python illustration

In a local environment with SQLAlchemy installed:

from sqlalchemy import create_engine, text

engine = create_engine("sqlite+pysqlite:///:memory:")
with engine.begin() as connection:
    connection.execute(text("CREATE TABLE notes (title TEXT NOT NULL)"))
    connection.execute(
        text("INSERT INTO notes (title) VALUES (:title)"),
        {"title": "Read"},
    )
    title = connection.execute(text("SELECT title FROM notes")).scalar_one()
    print(title)
engine.dispose()

Prepared output — not live execution:

Read

The value is bound as a parameter rather than added to the SQL string. Normal exit commits; an exception escaping the block causes rollback. The in-memory example disappears when the engine is disposed.

See the reasoning

Follow a transaction

See the bound value enter a temporary database and the transaction finish. This is a prepared demonstration, not live code execution.

Begin

Transaction stages
  1. Connectiontransaction openCurrent focus
  2. Insertpending
  3. Readpending
  4. Exitpending

engine.begin obtains a connection and starts a transaction.

Practical boundaries

SQLAlchemy supports different database backends through drivers and connection URLs. Protect credentials outside source code; grant only necessary permissions. Bound parameters represent values, not arbitrary table or column names: dynamic identifiers require a separate allowlist or safe query construction. Handle connection failures and transaction boundaries explicitly. Never expose a database directly to a browser merely because a client can form a query.

Real database durability, isolation, migrations, and concurrent access need backend-specific design. This demonstration does not add a database, backend, or learner tracking to Intuvo.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. What does an SQLAlchemy engine provide?
2. Why bind SQL parameters rather than interpolate untrusted values into SQL?
3. What happens when an exception escapes an engine.begin block?
4. Does this lesson add a database to Intuvo?

References and further reading