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.
| SQLite | PostgreSQL | MySQL / MariaDB | |
|---|---|---|---|
| Runs as | A file in your project | A separate server process | A separate server process |
| Concurrent writers | One | Many | Many |
| Network access | No | Yes (port 5432) | Yes (port 3306) |
| Strict types | No (values are flexible) | Yes | Yes |
| Best for | Tests, desktop apps, prototypes | Complex queries, JSON, correctness | Read-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
| Driver | Placeholder 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
- Copying
?placeholders into psycopg: you getsyntax error at or near "?". The driver's style is%s, and it does not care what type the value is —%sfor numbers too. - Hardcoding the password: it lands in Git history forever, even after you delete the line. Read credentials from environment variables or a secrets manager.
- Never closing connections: each open connection holds a server-side process. PostgreSQL defaults to 100 of them, then refuses everyone. Use
withblocks or a pool. - 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). - 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, andFOREIGN KEYare enforced even when a colleague edits rows by hand. - Store one
DATABASE_URL: a singlepostgresql://user:pass@host:5432/dbnamestring 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
- The Docker Database: Start PostgreSQL in a container, then connect from Python and create a
customerstable with aUNIQUEemail column. Try inserting the same email twice and catch the resulting error. - The Dialect Switch: Write one function
fetch_products(limit)that works against both SQLite and PostgreSQL, choosing the placeholder from an environment variable. - The Constraint Test: Add
CHECK (price >= 0)to a table, then attempt to insert-5from Python. Print the exception class and message, and explain why catching this beats validating only in Python.