DB-API
The DB-API (PEP 249) is the common interface for Python database drivers: connect, cursor, execute, fetchone/fetchall, and commit/rollback. sqlite3, psycopg, and mysqlclient all speak it.
Detailed Explanation
Without a shared API, every database would have its own query method and its own placeholder style. PEP 249 says: conn = connect(...) returns a connection. cur = conn.cursor() returns a cursor. cur.execute(sql, params) runs a statement. cur.fetchone() gets a row. conn.commit() persists a transaction. conn.rollback() undoes it. Context managers (with conn:, with closing(cur)) are widely supported even where the PEP was silent.
Parameter style differs by driver. sqlite3 uses ?. psycopg uses %s. Some use :name. You pass parameters as a second argument, never by concatenating strings. That is the SQL injection boundary. execute("... where id = ?", (user_id,)) is the pattern.
Rows are sequences by default. Many drivers can return dict-like rows (row_factory, RealDictCursor). Column names live on cursor.description. There is no standard ORM here; this is raw SQL plus a cursor.
Connections are not thread-safe in general. sqlite3 allows a check that the same thread is used. A pool owns connections; your request borrows one and returns it. Do not store a connection on a global that every thread shares.
sqlite3 ships with Python and is the usual teaching driver. Production Postgres or MySQL means installing a driver that implements the same API. SQLAlchemy's Core and Django's ORM sit on top of this layer.
Errors are subclasses of Error. IntegrityError is a constraint violation. Catch those, not Exception, when you mean "duplicate key".
Code Examples
import sqlite3
with sqlite3.connect(":memory:") as conn:
conn.execute("create table orders (id text, cents int)")
conn.execute("insert into orders values (?, ?)", ("11", 2500))
row = conn.execute("select cents from orders where id = ?", ("11",)).fetchone()
print(row[0]) # 2500# Wrong: string formatting is SQL injection.
# conn.execute(f"select * from orders where id = '{user_input}'")Common Gotchas
F-strings in SQL
injection. Always pass parameters separately.
Forgetting `commit`
sqlite3 may autocommit in some modes; Postgres will not. Be explicit or use `with conn:`.
Sharing one connection across threads
use a pool or a per-request connection.
Placeholder style is per driver
`?` vs `%s` is a portability tax. SQLAlchemy hides it.