Python Standard Library · Lesson 125 of 149

Python sqlite3

What you will learn

  • What SQLite is and when to use it
  • Connecting, creating tables, inserting and selecting
  • ? placeholders and SQL injection
  • fetchone, fetchall, Row objects
  • Transactions: commit, rollback, with con
  • Constraints and database errors

1. A database in a file

A database stores data in tables of rows and columns and answers questions written in SQL (Structured Query Language). Most databases are separate server programs, but SQLite is a complete SQL database stored in a single file (or in memory) with nothing to install: Python includes it as the sqlite3 module. It is used inside phones, browsers and many applications, and is ideal for small to medium data, prototypes and local storage. For many users writing at once, or huge data, use a server database such as PostgreSQL (the Pathkori site itself uses one in production).

You do not need to know SQL to follow along: each statement is explained. A full SQL course is a subject of its own.

import sqlite3

2. Connecting and creating a table

con = sqlite3.connect(":memory:")

connect(path) opens (or creates) the database file path. The special name ":memory:" creates a temporary database in memory, perfect for learning and tests. A connection (con) runs statements, and a cursor (what execute returns) gives access to results.

con.execute("""
    CREATE TABLE people (
        id   INTEGER PRIMARY KEY,
        name TEXT NOT NULL,
        age  INTEGER,
        city TEXT
    )
""")

A table has named columns with types. PRIMARY KEY gives each row a unique id (assigned automatically). NOT NULL means the column must have a value.

3. Inserting data: use placeholders

con.execute("INSERT INTO people (name, age, city) VALUES (?, ?, ?)",
            ("Rina", 25, "Dhaka"))

con.executemany("INSERT INTO people (name, age, city) VALUES (?, ?, ?)",
                [("Sam", 22, "Khulna"), ("Lee", 30, "Dhaka"), ("Amy", None, "Sylhet")])
con.commit()
  • Each ? is a placeholder; the values are passed separately, in a tuple. executemany repeats the statement for each tuple in a list.
  • Python's None is stored as the SQL NULL ("no value").
  • commit() saves the changes permanently (section 6).

Never build SQL with string formatting

Putting values into the SQL text with f-strings or + opens the door to SQL injection: the user's text becomes part of the command. Compare, on the table above, a "name" that a user typed as x' OR '1'='1:

name = "x' OR '1'='1"
bad = con.execute(f"SELECT COUNT(*) FROM people WHERE name = '{name}'").fetchone()[0]
good = con.execute("SELECT COUNT(*) FROM people WHERE name = ?", (name,)).fetchone()[0]
print("unsafe matched rows:", bad, "| safe matched rows:", good)
unsafe matched rows: 4 | safe matched rows: 0

The unsafe version let the text rewrite the question and matched every row; the placeholder version treated the whole text as a name and matched none. A real attacker can use the same trick to read or delete data. Always pass values with ? placeholders, for every statement that includes outside data. (Placeholders work only for values, not for table or column names.)

Quick check: why `execute(sql, (value,))` with a one-item tuple and a comma?

The second argument must be a sequence; (value,) is a tuple with one item, while (value) is just value in parentheses.

4. Querying

cur = con.execute("SELECT * FROM people")
print(cur.fetchall())
[(1, 'Rina', 25, 'Dhaka'), (2, 'Sam', 22, 'Khulna'), (3, 'Lee', 30, 'Dhaka'), (4, 'Amy', None, 'Sylhet')]
Method Returns
cur.fetchone() the next row, or None when finished
cur.fetchall() all remaining rows as a list
cur.fetchmany(n) up to n rows
for row in cur rows one at a time (best for big results)

Rows are tuples. Some typical queries:

cur = con.execute("SELECT name, age FROM people WHERE city = ? ORDER BY name", ("Dhaka",))
print(cur.fetchone(), cur.fetchone(), cur.fetchone())

print(con.execute("SELECT COUNT(*), AVG(age), MAX(age) FROM people").fetchone())

print(con.execute(
    "SELECT city, COUNT(*) FROM people GROUP BY city ORDER BY COUNT(*) DESC, city").fetchall())

for row in con.execute("SELECT name FROM people WHERE age IS NULL"):
    print(row)
('Lee', 30) ('Rina', 25) None
(4, 25.666666666666668, 30)
[('Dhaka', 2), ('Khulna', 1), ('Sylhet', 1)]
('Amy',)
  • WHERE filters rows, ORDER BY sorts, GROUP BY groups for counts and sums, COUNT, AVG, MAX are aggregate functions.
  • The average ignores NULL (the three known ages: 25, 22, 30).
  • Test for missing values with IS NULL, not = NULL.

Row objects

Set row_factory = sqlite3.Row and rows can be read by column name, and converted to dictionaries:

con.row_factory = sqlite3.Row
r = con.execute("SELECT * FROM people WHERE name = 'Rina'").fetchone()
print(r["name"], r["age"])
print(dict(r))
print(r.keys())
Rina 25
{'id': 1, 'name': 'Rina', 'age': 25, 'city': 'Dhaka'}
['id', 'name', 'age', 'city']

5. Updating and deleting

cur = con.execute("UPDATE people SET age = age + 1 WHERE city = ?", ("Dhaka",))
print(cur.rowcount)

cur = con.execute("DELETE FROM people WHERE name = ?", ("Amy",))
print(cur.rowcount)

cur = con.execute("INSERT INTO people (name) VALUES ('Zed')")
print(cur.lastrowid)
2
1
4

rowcount is the number of rows changed. lastrowid is the id given to the last inserted row. It is 4 here: Amy's row 4 had just been deleted, and SQLite reuses the highest number when the column is a plain INTEGER PRIMARY KEY (add the word AUTOINCREMENT to forbid reuse). Always include a WHERE in UPDATE and DELETE, or every row is changed.

6. Transactions: all or nothing

Changes happen inside a transaction: they become permanent at commit(), and rollback() discards them. The connection works as a context manager that does this for you:

con.commit()                      # first save everything done so far (see below)
try:
    with con:
        con.execute("UPDATE people SET age = 99 WHERE name = 'Rina'")
        raise RuntimeError("fail")
except RuntimeError:
    pass
print(con.execute("SELECT age FROM people WHERE name = 'Rina'").fetchone()[0])

with con:
    con.execute("UPDATE people SET age = 50 WHERE name = 'Rina'")
print(con.execute("SELECT age FROM people WHERE name = 'Rina'").fetchone()[0])
26
50

In the first block the error undid the change (Rina stayed 26); in the second the block ended normally and committed. The first line, con.commit(), matters: a rollback discards everything since the last commit, not just the changes inside the failing block. Without it, the failed block would also have undone the earlier, still uncommitted statements of section 5 (the age update, the delete and the new row), and the first number printed would have been 25 instead of 26 (this was found when the lessons' code was run again in order). Note that with con does not close the connection: call con.close() yourself, or use contextlib.closing(con) (lesson 14.6). Transactions keep related changes together: if money moves between two accounts, either both updates happen or neither does.

7. Constraints and errors

The database can enforce rules and raises exceptions from sqlite3 (all kinds of sqlite3.Error):

con.execute("INSERT INTO people (age) VALUES (5)")
sqlite3.IntegrityError: NOT NULL constraint failed: people.name
con.execute("SELECT * FROM nope")
con.execute("SELEC 1")
sqlite3.OperationalError: no such table: nope
sqlite3.OperationalError: near "SELEC": syntax error

Using a closed connection gives sqlite3.ProgrammingError: Cannot operate on a closed database. Catch these like any exception (lesson 14.1). Useful column rules: NOT NULL, UNIQUE, DEFAULT value, CHECK (condition), PRIMARY KEY, and FOREIGN KEY links between tables.

8. Types and joins

SQLite has a few storage types: INTEGER, REAL, TEXT, BLOB (bytes) and NULL. They map to Python's int, float, str, bytes and None:

con.execute("CREATE TABLE ty (a INTEGER, b REAL, c TEXT, d BLOB, e)")
con.execute("INSERT INTO ty VALUES (?, ?, ?, ?, ?)", (1, 2.5, "x", b"\x00\x01", None))
print(tuple(con.execute("SELECT * FROM ty").fetchone()))
(1, 2.5, 'x', b'\x00\x01', None)

SQLite is flexible about types: it let the text 'text' into an INTEGER column, and stored it as text. Other databases are stricter. SQLite has no date type; store dates as ISO text (2026-03-05, lesson 17.1), which sorts and compares correctly.

A join combines tables through a shared value:

con.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, person_id INTEGER, total REAL)")
con.executemany("INSERT INTO orders (person_id, total) VALUES (?, ?)",
                [(1, 10.5), (1, 4.5), (2, 7.0)])
q = """SELECT p.name, COUNT(o.id), SUM(o.total)
       FROM people p LEFT JOIN orders o ON o.person_id = p.id
       GROUP BY p.id ORDER BY p.id"""
print([tuple(r) for r in con.execute(q)])
[('Rina', 2, 15.0), ('Sam', 1, 7.0), ('Lee', 0, None), ('Zed', 0, None)]

LEFT JOIN keeps people with no orders (Lee and Zed show 0 orders and no total). sqlite_master lists the tables.

9. A file database

Use a file name instead of ":memory:" to keep data between runs:

c2 = sqlite3.connect("t.db")
c2.execute("CREATE TABLE t (x)")
c2.execute("INSERT INTO t VALUES (1)")
c2.commit()
c2.close()

c3 = sqlite3.connect("t.db")
print(c3.execute("SELECT * FROM t").fetchall())
c3.close()
[(1,)]

Without commit() the insert would be lost. Back up a SQLite database by copying the file while nothing is writing to it, or with con.backup(...).

Worked example: an expense tracker

An expense table with a CHECK rule, functions to add rows, summarise by category and list one month, and proof that the data survives in the file.

import sqlite3
from contextlib import closing


def connect(path):
    con = sqlite3.connect(path)
    con.row_factory = sqlite3.Row
    con.execute("""
        CREATE TABLE IF NOT EXISTS expense (
            id INTEGER PRIMARY KEY,
            day TEXT NOT NULL,
            category TEXT NOT NULL,
            amount REAL NOT NULL CHECK (amount > 0),
            note TEXT
        )""")
    return con


def add(con, day, category, amount, note=None):
    with con:
        cur = con.execute(
            "INSERT INTO expense (day, category, amount, note) VALUES (?, ?, ?, ?)",
            (day, category, amount, note))
    return cur.lastrowid


def by_category(con):
    rows = con.execute(
        "SELECT category, COUNT(*) AS n, ROUND(SUM(amount), 2) AS total "
        "FROM expense GROUP BY category ORDER BY total DESC")
    return [(r["category"], r["n"], r["total"]) for r in rows]


def in_month(con, month):
    return [dict(r) for r in con.execute(
        "SELECT day, category, amount FROM expense WHERE day LIKE ? ORDER BY day",
        (month + "%",))]


with closing(connect("expenses.db")) as con:
    add(con, "2026-03-01", "food", 12.5, "lunch")
    add(con, "2026-03-02", "transport", 3.0)
    add(con, "2026-03-05", "food", 8.25)
    add(con, "2026-04-01", "rent", 400)
    try:
        add(con, "2026-04-02", "food", -5)
    except sqlite3.IntegrityError as e:
        print("rejected:", e)
    print(by_category(con))
    print(in_month(con, "2026-03"))

with closing(connect("expenses.db")) as con:
    print(con.execute("SELECT COUNT(*) FROM expense").fetchone()[0], "rows saved in the file")
rejected: CHECK constraint failed: amount > 0
[('rent', 1, 400.0), ('food', 2, 20.75), ('transport', 1, 3.0)]
[{'day': '2026-03-01', 'category': 'food', 'amount': 12.5}, {'day': '2026-03-02', 'category': 'transport', 'amount': 3.0}, {'day': '2026-03-05', 'category': 'food', 'amount': 8.25}]
4 rows saved in the file
Part Idea
CREATE TABLE IF NOT EXISTS safe to run on every start
CHECK (amount > 0) the database itself refuses the negative amount
with con: in add each insert is its own transaction
? placeholders (including month + "%" for LIKE) no values pasted into the SQL text
closing(...) the connection is closed after each block
the second connect the four good rows are still there

The expenses are made up. Because dates are ISO text, LIKE '2026-03%' selects a month.

Common mistakes

  • Building SQL with f-strings or + (SQL injection).
  • Forgetting commit(), so changes vanish.
  • UPDATE or DELETE without WHERE.
  • Writing (value) instead of (value,) for one parameter.
  • Not closing connections.
  • Comparing with = NULL instead of IS NULL.
  • Using SQLite for heavy multi-user write loads.
  • Storing money as REAL where exact decimals matter (store whole cents as integers, lesson 3.4).

Key takeaways

  • sqlite3 is a full SQL database in one file (or memory), included with Python.
  • Pass values with ? placeholders, never by formatting strings: this prevents SQL injection.
  • execute, executemany, fetchone, fetchall, and row_factory = sqlite3.Row cover most work.
  • Changes need commit(); with con: commits on success and rolls back on error, but does not close.
  • Constraints (NOT NULL, CHECK, UNIQUE) make the database enforce rules; errors come as sqlite3.Error subclasses.

Practice

1. Why is con.execute(f"SELECT * FROM t WHERE name = '{n}'") dangerous?

Show answer

Text typed by a user becomes part of the SQL, so it can change the command (SQL injection). Use execute("... WHERE name = ?", (n,)).

2. What happens to inserted rows if you never call commit() and the program ends?

Show answer

The changes are lost; they were never made permanent.

3. How do you read a column by name from a row?

Show answer

Set con.row_factory = sqlite3.Row, then use row["name"].

4. What does with con: do when an exception occurs in the block?

Show answer

It rolls back the transaction (the changes are discarded) and the exception continues. It does not close the connection.

5. Write a query counting people older than 20.

Show answer
con.execute("SELECT COUNT(*) FROM people WHERE age > ?", (20,)).fetchone()[0]

6. How should dates be stored in SQLite?

Show answer

As ISO text such as 2026-03-05 (or as numbers), because SQLite has no date type; ISO text sorts and compares correctly.