Home / Learn Secure SQL / Python: sqlite3 Module

Python: sqlite3 Module

The standard library driver, with a nearly identical API to PostgreSQL/MySQL drivers.

Quick summaryThe standard library driver, with a nearly identical API to PostgreSQL/MySQL drivers.

How to think about this

Python DB-API patterncursor.execute(sql,params)driver binds paramssafelycursor.fetchall()
Python DB-API pattern

What it is

Python's built-in sqlite3 module uses cursor.execute(sql, params) with ? placeholders, a pattern shared almost exactly by psycopg2 and MySQL drivers.

Why it matters

Because the pattern is so consistent across Python drivers, learning it once here transfers almost directly to the next two lessons.

Mechanically speaking

Pass the SQL with ? placeholders as the first argument to execute(), and a tuple or list of values as the second argument.

Shows up in

  • Web application code review
  • Backend development
  • Database administration
Python sqlite3
import sqlite3
conn = sqlite3.connect('shop.db')
cur = conn.cursor()
cur.execute('SELECT * FROM users WHERE email = ?', (email,))
row = cur.fetchone()
Careful:Never use f'SELECT * FROM users WHERE email = '{email}''' or "...".format(email) to build the SQL string; both reintroduce the core problem.

Check yourself

1. In Python's DB-API, parameters go...