PostgreSQL & MySQL: Beyond SQLite

PostgreSQL & MySQL: Beyond SQLite in Python: SQLite is a file. That is its superpower and its ceiling.

Concept Explanation

SQLite is a file. That is its superpower and its ceiling. There is no server process, no port, no user accounts — you open a path and you are talking to a database. Perfect for a desktop app, a test suite, or a prototype.

The moment two web servers need to write at the same time, that model breaks. SQLite allows exactly one writer at a time and locks the whole file to do it. Your second request waits, then times out. This is when you graduate to a client/server database.

SQLitePostgreSQLMySQL / MariaDB
Runs asA file in your projectA separate server processA separate server process
Concurrent writersOneManyMany
Network accessNoYes (port 5432)Yes (port 3306)
Strict typesNo (values are flexible)YesYes
Best forTests, desktop apps, prototypesComplex queries, JSON, correctnessRead-heavy web apps, WordPress-era stacks

If you cannot decide, choose PostgreSQL. It has the strictest correctness guarantees, the richest type system (real arrays, real JSON, real dates), and it is the default in almost every modern Python deployment guide.

DB-API 2.0: One Interface, Many Engines

Python standardised database access in PEP 249. Every driver — sqlite3, psycopg, mysql-connector-python — exposes the same four moves:

conn = driver.connect(...)     # 1. open
cur = conn.cursor()            # 2. get a cursor
cur.execute(sql, params)       # 3. run SQL
conn.commit()                  # 4. persist

Learn it once and you can drive any of them.

Installing the Drivers

pip install "psycopg[binary]"        # PostgreSQL (modern, v3)
pip install mysql-connector-python  # MySQL / MariaDB

The One Real Gotcha: Placeholders Differ

DriverPlaceholder style
sqlite3?
psycopg%s
mysql-connector%s

%s is not string formatting. Never use % or an f-string to build it yourself — pass the tuple as a second argument and let the driver escape the values.


Code Example #1 (Basic)

The same script shape, pointed at PostgreSQL.

import os
import psycopg

# Credentials come from the environment, never from source code
conn = psycopg.connect(
    host=os.environ.get("PGHOST", "localhost"),
    dbname=os.environ.get("PGDATABASE", "shop"),
    user=os.environ["PGUSER"],
    password=os.environ["PGPASSWORD"],
)

with conn, conn.cursor() as cur:
    cur.execute("""
        CREATE TABLE IF NOT EXISTS products (
            id      SERIAL PRIMARY KEY,
            name    TEXT NOT NULL,
            price   NUMERIC(10, 2) NOT NULL CHECK (price >= 0)
        )
    """)
    cur.execute(
        "INSERT INTO products (name, price) VALUES (%s, %s) RETURNING id",
        ("Mechanical Keyboard", 129.99),
    )
    new_id = cur.fetchone()[0]
    print("Inserted product", new_id)

conn.close()

Two PostgreSQL features to notice: SERIAL auto-numbers the primary key, and RETURNING id gives you the generated key in the same round trip — no second query needed.

Code Example #2 (Intermediate)

One codebase, either engine, chosen by configuration.

import os
from contextlib import contextmanager

ENGINE = os.environ.get("DB_ENGINE", "sqlite")

@contextmanager
def get_cursor():
    """Yield a cursor for whichever engine is configured, then clean up."""
    if ENGINE == "postgres":
        import psycopg
        conn = psycopg.connect(os.environ["DATABASE_URL"])
        placeholder = "%s"
    else:
        import sqlite3
        conn = sqlite3.connect("local.db")
        placeholder = "?"

    try:
        cur = conn.cursor()
        cur.ph = placeholder      # remember the dialect for callers
        yield cur
        conn.commit()
    except Exception:
        conn.rollback()           # never leave a half-written transaction
        raise
    finally:
        conn.close()

with get_cursor() as cur:
    cur.execute(f"SELECT name FROM products WHERE price < {cur.ph}", (200,))
    print([row[0] for row in cur.fetchall()])

The f-string here interpolates only the placeholder token, never the user's value — the value still travels as a parameter. That is the safe version of the pattern.

For anything more elaborate than this, stop hand-rolling and use SQLAlchemy, which abstracts the dialect properly.


Common Mistakes

  1. Copying ? placeholders into psycopg: you get syntax error at or near "?". The driver's style is %s, and it does not care what type the value is — %s for numbers too.
  2. Hardcoding the password: it lands in Git history forever, even after you delete the line. Read credentials from environment variables or a secrets manager.
  3. Never closing connections: each open connection holds a server-side process. PostgreSQL defaults to 100 of them, then refuses everyone. Use with blocks or a pool.
  4. Opening a new connection per request: the TCP handshake plus authentication costs more than most queries. Use a pool (psycopg_pool, or SQLAlchemy's built-in pool).
  5. Assuming SQLite behaviour carries over: SQLite happily stores the string "abc" in an INTEGER column. PostgreSQL rejects it. Code that "worked locally" can fail on deploy — which is a feature, not a bug.

Best Practices

  • Develop against the engine you deploy to: run PostgreSQL locally in Docker (docker run -e POSTGRES_PASSWORD=dev -p 5432:5432 postgres) rather than discovering dialect differences in production.
  • Use a connection pool: from psycopg_pool import ConnectionPool — open it once at start-up, borrow per request.
  • Put constraints in the schema, not only in Python: NOT NULL, CHECK, UNIQUE, and FOREIGN KEY are enforced even when a colleague edits rows by hand.
  • Store one DATABASE_URL: a single postgresql://user:pass@host:5432/dbname string is easier to swap per environment than five separate settings.
  • Always rollback() on error: an abandoned open transaction can hold locks that block every other writer.

Practice Exercises

  1. The Docker Database: Start PostgreSQL in a container, then connect from Python and create a customers table with a UNIQUE email column. Try inserting the same email twice and catch the resulting error.
  2. The Dialect Switch: Write one function fetch_products(limit) that works against both SQLite and PostgreSQL, choosing the placeholder from an environment variable.
  3. The Constraint Test: Add CHECK (price >= 0) to a table, then attempt to insert -5 from Python. Print the exception class and message, and explain why catching this beats validating only in Python.