Home / Learn Secure SQL / Python: psycopg2 for PostgreSQL
Python: psycopg2 for PostgreSQL
The most common PostgreSQL driver, same pattern as sqlite3.
The gistThe most common PostgreSQL driver, same pattern as sqlite3.
The idea, explained simply
What it is
psycopg2 uses the same cursor.execute(sql, params) pattern as sqlite3, but with %s as the placeholder instead of ?.
Why it matters
Because the API is so similar to sqlite3, switching between SQLite in development and PostgreSQL in production usually only changes the placeholder character and the connection setup.
Mechanically speaking
Use %s placeholders (even for non-string types; psycopg2 adapts them), and always pass values as a tuple/list second argument.
Shows up in
- Web application code review
- Backend development
- Database administration
import psycopg2
conn = psycopg2.connect('dbname=shop user=app')
cur = conn.cursor()
cur.execute('SELECT * FROM users WHERE email = %s', (email,))
row = cur.fetchone()Careful:psycopg2's %s is its own placeholder syntax, not Python's % string formatting operator — do not use cur.execute(sql % email), which is string formatting, not parameter binding.
Check yourself
1. psycopg2's placeholder character is...
%s for psycopg2.