Skip to chapter content
navan✳THE BUILD LABPYTHON / GUIDE
0/26 read
CHAPTER 16 / 26 · DOCUMENTS AND SERVICES

Storing records with SQLite.

Use a local SQL database for durable records and safe queries.

BY NAVAN SAMI5 MIN READTHEORY FIRST
01 / THE BASICS

Start here.

A database stores records so they can be found and changed later. SQLite keeps its database in a local file and understands SQL, a language for defining tables and asking questions of rows. A table has named columns with declared kinds of data, and each row represents one record. An INSERT adds a row, SELECT reads rows, UPDATE changes them, and DELETE removes them. Python's sqlite3 module connects to the file and sends SQL statements.

The connection represents access to the database. A cursor executes a statement and exposes returned rows. A transaction groups changes so they can be committed together or rolled back if something fails. commit makes pending changes durable. This matters when several related rows must either all be stored or none should be. Closing the connection releases the resource when work ends.

Values from variables must be passed as parameters, usually with ? placeholders, rather than joined into SQL text. The database then treats a value as data even if it contains quotes or SQL-looking characters. SQL structure, such as table and column names, is different and should come from known code. When reading an example, separate the SQL question from the Python values supplied to it, then trace what rows the database will return.

02 / THE IDEA

Build the model.

SQLite stores tables in a local database file and is available through Python's sqlite3 standard-library module. A table has named columns and declared types; rows hold records. It is a good fit when a script needs reliable lookup, filtering, or updates across runs without running a separate database server.

Design a small schema from the questions the program needs to answer. Give each record a stable identifier, choose required fields, and add uniqueness constraints where duplicates would be harmful. Then keep SQL statements as explicit, reviewable operations instead of scattering string fragments across the code.

03 / UNDER THE SURFACE

How it works.

A connection represents a session with the database. Use a context manager to commit a successful group of changes or roll back on error, and close the connection when finished. A cursor or connection.execute runs SQL; fetchone and fetchall read query results. A SELECT does not change records, while INSERT, UPDATE, and DELETE do.

Never insert user-supplied values into SQL by formatting a string. Use ? placeholders and pass a tuple of values. The driver sends the values separately so text such as an apostrophe is handled correctly and cannot become SQL syntax. Placeholders are for values, not table or column names; choose identifiers from your own trusted code.

Transactions group related changes. If a task requires both an insert and an update, they should either both commit or both fail. SQLite is local and durable, but it does not remove the need for backups or a migration plan when the schema changes. Test with a temporary database before touching a real one.

04 / A WORKED EXAMPLE

Read it line by line.

example.py
import sqlite3
with sqlite3.connect(':memory:') as db:
    db.execute('CREATE TABLE tasks (id INTEGER PRIMARY KEY, title TEXT NOT NULL)')
    db.execute('INSERT INTO tasks (title) VALUES (?)', ('Review notes',))
    row = db.execute('SELECT title FROM tasks WHERE id = ?', (1,)).fetchone()
    print(row[0])

The in-memory database lasts only for this connection. CREATE TABLE defines a required title. INSERT uses a placeholder for the value, and the SELECT uses another placeholder for the identifier. fetchone returns a row tuple, so row[0] prints Review notes. Replace ':memory:' with a file path when persistence is required.

05 / ANOTHER EXAMPLE

See the rule again.

example-2.py
import sqlite3
with sqlite3.connect(':memory:') as db:
    db.execute('CREATE TABLE tasks (title TEXT)')
    db.executemany('INSERT INTO tasks VALUES (?)', [('One',), ('Two',)])
    count = db.execute('SELECT COUNT(*) FROM tasks').fetchone()[0]
    print(count)

The output is 2. executemany repeats the same parameterised statement for the supplied one-item tuples. COUNT(*) is calculated by the database and fetchone returns its single result row.

06 / REMEMBER THIS

A mistake to avoid.

The with sqlite3.connect(...) block manages transaction commit or rollback, but it does not guarantee the connection is closed immediately at block exit. Close it explicitly or use contextlib.closing when precise lifetime matters.

Finished this chapter?
Built with curiosity. By Navan Sami. ↗Python · Understand the idea, then write the code.