Complete worked example
python
from contextlib import closing
import sqlite3
def store_roles(path, rows):
with closing(sqlite3.connect(path)) as connection:
with connection:
connection.execute("CREATE TABLE IF NOT EXISTS roles (id TEXT PRIMARY KEY NOT NULL CHECK(length(id)>0), title TEXT NOT NULL, country TEXT NOT NULL)")
for row in rows:
connection.execute("INSERT INTO roles VALUES (?, ?, ?) ON CONFLICT(id) DO UPDATE SET title=excluded.title, country=excluded.country", row)
return [list(row) for row in connection.execute("SELECT id, title, country FROM roles ORDER BY id")]- Reasoning
- Store a small batch with an explicit transaction boundary and close the connection independently of transaction exit. Compare the stated values and failure boundary before changing the implementation.