liveBook · Manning

SQLAlchemy

As explained in Build Python Web Apps with Streamlit

SQLAlchemy is a Python database toolkit and object-relational mapping library that provides database connectivity, SQL execution, and transaction management.

A Streamlit app needs a way to read and change PostgreSQL data through Python. SQLAlchemy is the database toolkit Streamlit uses behind `st.connection` to manage connections and execute queries. Install it with `pip install sqlalchemy`; PostgreSQL also needs the `psycopg2-binary` adapter. section 8.2.5

Listing 8.1 The Database class
import streamlit as st
from sqlalchemy import text

class Database:
  def __init__(self):
    self.conn = st.connection("haikuconn", type="sql")

  def execute_query(self, query, params={}, write=False):
    with self.conn.session as session:
      try:
        result = session.execute(text(query), params)
        if write:
          session.commit()
        return result.fetchall()
      except Exception:
        if write:
          session.rollback()
        raise

The `Database` class keeps connection logic in one place. Its `execute_query` method runs SQL with parameters, returns fetched rows, commits writes, and rolls back failed writes. section 8.2.5

Read rows in the app

After configuring the named connection, call `database.execute_query('SELECT * FROM haikus')` and pass the results to `st.write` to display the table. section 8.2.5

How Build Python Web Apps with Streamlit covers it

How deep it goes
Shows SQLAlchemy through `st.connection`, `text()`, and sessions, without developing SQLAlchemy internals.
Examples
Uses a `Database` class and a `SELECT` query whose rows appear in Streamlit.
What it assumes
Assumes a configured PostgreSQL database and builds on manually inserting and querying rows.
What you can do after
Apply it via Streamlit’s `st.connection` to execute queries and commit or roll back writes.
How it connects
Links SQLAlchemy to Streamlit, PostgreSQL, psycopg2, SQL queries, and transactions.

Also explained in

Compare how 4 books explain SQLAlchemy →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build Python Web Apps with Streamlit. The section links point to the parts of the book it draws on.