liveBook · Manning

Connection string

As explained in Build Python Web Apps with Streamlit

A connection string is a structured value containing the address, port, credentials, and database name needed to connect to a data service.

A Streamlit app needs a way to find its PostgreSQL database before it can save or retrieve data. A connection string puts the required details in one value: the server address, port, username, password, and database name. The PostgreSQL port is 5432 by default, unless it was changed during installation. section 8.2.5

Connect to a local database

The pattern is `postgresql://<username>:<password>@<server address>:<port>/<database name>`. For a local server, the address can be `localhost`. Put the completed value under `url` in the named connection’s `.streamlit/secrets.toml` entry. Replace the example password with the real one, and do not check `secrets.toml` into Git. section 8.2.5

Listing 8.2 The .streamlit/secrets.toml file
[connections.haikuconn]
url = "postgresql://haiku_lord:password@localhost:5432/haikudb"    #1

Shows how a PostgreSQL URL is assigned to `url` under `[connections.haikuconn]`; the password shown is a placeholder. section 8.2.5

The name in that entry must match the name passed to `st.connection("haikuconn", type="sql")`. Once connected, the app can use its database class to run a `SELECT` query and display the returned rows. section 8.2.5

For production, use the connection string supplied by the managed PostgreSQL service instead of the local one. Neon’s Quick Start provides a string with credentials and a hosted server address; its example also includes `sslmode=require`. Keep the string safe. Set up the required tables on the hosted database before expecting the app’s queries to work there. section 8.6.1

How Build Python Web Apps with Streamlit covers it

How deep it goes
Defines the URL fields and works through local and hosted configuration, without detailing PostgreSQL connection internals.
Examples
Shows a local `secrets.toml` URL and a Neon Quick Start URL for a hosted database.
What it assumes
Assumes a Streamlit app and PostgreSQL database, then teaches how to assemble the connection URL from their connection details.
What you can do after
Operate/configure it by supplying the appropriate PostgreSQL URL for a local or Neon-hosted Streamlit SQL connection.
How it connects
Links PostgreSQL, Streamlit SQL connections, secrets.toml, database queries, and managed databases.

Also explained in

Compare how 7 books explain connection string →

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.