Part 12 / Topic 9 of 11
sqlite3 in Python
The steps are always the same:
conn = sqlite3.connect("shop.db")opens (or creates) a database file.":memory:"makes a temporary one in RAM.conn.execute(sql, values)runs one SQL statement. It returns a cursor: an object that walks through the result rows. (conn.cursor()makes one by hand;conn.executeis a shortcut.)cursor.fetchone()gives the next row (orNone);cursor.fetchall()gives a list of all rows. You can also loop over the cursor.- Changes are not saved until you commit.
with conn:commits at the end of the block, or rolls back (undoes everything) if an error happens. conn.close()when done. Note:with conn:does not close the connection.
Think of with conn: as a shopping basket: everything is paid for together at the till, or put back if something goes wrong.
import sqlite3
conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row # read columns by name: row["name"]
conn.execute("CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, city TEXT)")
customers = [("Asha", "Pune"), ("Ravi", "Mumbai"), ("Meera", "Pune")]
with conn: # commit at the end
conn.executemany( # one statement, many rows
"INSERT INTO customers (name, city) VALUES (?, ?)", customers
)
cursor = conn.execute("SELECT * FROM customers WHERE city = ? ORDER BY name", ("Pune",))
for row in cursor.fetchall():
print(row["id"], row["name"])
# 1 Asha
# 3 Meera
row = conn.execute("SELECT COUNT(*) AS n FROM customers").fetchone()
print(row["n"]) # 3
print(dict(row)) # {'n': 3}
conn.close()
Parameterised queries: always use ?
Put a ? where a value goes, and pass the values as a tuple (note the comma in ("Pune",)). sqlite3 sends the values separately from the SQL, so they can never be run as SQL.
SQL injection is an attack where a user types SQL code into an input box. If you build the query with an f-string, their text becomes part of your SQL.
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (name TEXT, password TEXT)")
conn.execute("INSERT INTO users VALUES (?, ?)", ("asha", "secret1"))
conn.execute("INSERT INTO users VALUES (?, ?)", ("ravi", "secret2"))
typed = "nobody' OR '1'='1" # what an attacker types as a user name
# NEVER: the quote in `typed` ends the string, and OR '1'='1' is always true
bad = f"SELECT name FROM users WHERE name = '{typed}'"
print(conn.execute(bad).fetchall()) # [('asha',), ('ravi',)] <- all users leaked!
# ALWAYS: the value is passed separately and is only ever data
good = "SELECT name FROM users WHERE name = ?"
print(conn.execute(good, (typed,)).fetchall()) # []
conn.close()
f-string / + |
? placeholders |
|
|---|---|---|
| Safe from SQL injection | ❌ No | ✅ Yes |
Quotes in names (D'Souza) |
❌ Breaks the SQL | ✅ Just works |
| Rule | Never for values | Always for values |
Full program: examples/05_sqlite_orders.py (every SQL statement from section 8, run from Python).
🔍 Going deeper:
?works only for values, not for table or column names. If those must vary, pick them from a fixed list you wrote yourself.cursor.lastrowidgives the id of the row you just inserted;cursor.rowcounttells how many rows anUPDATE/DELETEchanged.
Read more: the official sqlite3 documentation.
Done here? The practice set for Part 12 — 8 exercises with solutions — is on the part page.