Databases

Server-side SQL drivers — the default and easiest way to talk to a database from a Pyodide app.

The Database resource type lets your app run pycorner.connect("name").execute(sql) against PostgreSQL or MySQL. The driver runs on PyCorner’s backend; results are serialized to JSON and returned to Pyodide. No client-side driver, no SSL juggling, no socket-in-the-browser tricks.

Why this is the default for DBs

The natural alternative — running a pure-Python driver like pg8000 inside Pyodide and tunneling its TCP — works (see Raw TCP) but has limits:

Mode 1 sidesteps all of that.

Create a resource

Resources → Databases tab → New Database.

Use it from your app

The client library wraps a tiny DB-API 2.0 facade. Each execute is a separate HTTPS POST under the hood — there’s no client-side connection or transaction state.

import pycorner
import streamlit as st

db = pycorner.connect("proddb")

cur = db.cursor()
cur.execute("SELECT id, name, status FROM orders WHERE status = %s", ("pending",))
rows = cur.fetchall()

st.write(f"{len(rows)} pending orders")
st.table([dict(zip([d[0] for d in cur.description], r)) for r in rows])

Parameter binding follows the driver:

Render gotcha: st.dataframe looks empty in stlite because pyarrow is mocked. Use st.table(rows) or st.write(rows) when displaying query results.

Multi-query sessions

You can run multiple queries on the same db instance — every call is just another POST. There’s no implicit transaction across calls, but you can run a session-scoped setup like setting search_path once by including it in your get_conn() helper:

@st.cache_resource
def get_conn():
    conn = pycorner.connect("proddb")
    conn.cursor().execute("SET search_path TO sample, public")
    return conn

@st.cache_resource keeps the same logical “connection” for the lifetime of the Streamlit session. (Logical, not physical — each execute is still a fresh POST, but you don’t have to re-establish it on every rerun.)

Security & isolation

Server-side errors

Driver errors (bad SQL, connection refused, auth failure) come back as a JSON response with HTTP 502 and {"error": "..."}. The client library raises RuntimeError with the message — wrap in a try/except if you want to render the error nicely:

try:
    rows = db.execute("SELECT bad_column FROM orders").fetchall()
except RuntimeError as e:
    st.error(str(e))

When to pick Mode 3 instead

If your customer specifically wants the database connection to be a real socket (e.g. for streaming COPY, LISTEN/NOTIFY, or just because they prefer the native driver experience), use a Raw TCP resource with pycorner.tunnel.install() and pg8000.connect() directly. See Raw TCP.