Thuta Learning
Python
AdvancedProgrammingBeginner

SQLite Basics (Enhanced)

PythonLesson 5135 min

What you'll walk away with

  • Open and close a file database or an in-memory :memory: database with sqlite3.connect()
  • Write parameterised queries with ? placeholders to prevent SQL injection
  • Run INSERT, SELECT, UPDATE and DELETE and use fetchall(), rowcount and sqlite3.Row
  • Explain how NOT NULL, UNIQUE and CHECK constraints and with conn: transactions protect the data

Explain it simply

Explain it simply

SQLite is a complete database that lives in a single file. Unlike PostgreSQL or MySQL, there is no separate server to install and run: it ships with Python as the sqlite3 module. Phone apps and web browsers use SQLite to store their data too.

Like a spreadsheet file it has tables, rows and columns, but you ask questions in SQL, and the database itself enforces rules such as "age cannot be negative" or "no duplicate emails".

Problem → Why → Solution

The problem: f-string SQL and a forgotten commit

The code below has two bugs. The first query pastes the user's input into SQL with an f-string, so typing x' OR '1'='1 makes the WHERE condition always true and returns every user. The second part closes the connection after an INSERT without committing, so the new row silently disappears without a single error.

unsafe_db.py
name = input("Search user: ")          # someone types:  x' OR '1'='1
rows = conn.execute(f"SELECT * FROM users WHERE name = '{name}'").fetchall()
# -> SELECT * FROM users WHERE name = 'x' OR '1'='1'   (every user!)

conn.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Sai", 25))
conn.close()                            # no commit: the insert is thrown away

Why does this happen?

The f-string splices the user's text into the SQL code itself, so a single quote can change what the query means. A ? placeholder sends the SQL and the values separately, so a value can never become code. The commit problem arises because sqlite3 implicitly opens a transaction before INSERT, UPDATE or DELETE, and closing the connection without committing rolls those changes back.

Core concept: connections, queries and transactions

sqlite3.connect("app.db") opens a file database, creating it if needed, while sqlite3.connect(":memory:") gives a database that lives in RAM and vanishes when the connection closes, which is ideal for tests and experiments. conn.execute(sql, params) is a shortcut that creates a cursor and runs the SQL. Read SELECT results with fetchone(), fetchall() or a plain for loop. Setting conn.row_factory = sqlite3.Row lets you read columns by name, as in row["name"].

Never assemble values into the SQL string yourself. Use ? placeholders with a tuple such as ("Sai", 25), or :name placeholders with a dict, and executemany() inserts many rows with one query. Placeholders work only for values, never for table or column names. After an UPDATE or DELETE, cursor.rowcount tells you how many rows were affected, and after an INSERT, cursor.lastrowid gives the new id.

Constraints enforce rules at the database level: violating NOT NULL, UNIQUE or CHECK (age >= 0) raises sqlite3.IntegrityError. An INTEGER PRIMARY KEY column assigns ids automatically, so add AUTOINCREMENT only if ids of deleted rows must never be reused. SQLite is flexible about column types (type affinity) and by default does not stop text from landing in an INTEGER column; use a STRICT table when you want it to.

A transaction makes a group of changes all-or-nothing. A with conn: block commits on success and rolls back on an exception, but it does not close the connection; call conn.close() separately. SQLite allows one writer at a time, which suits embedded apps, CLI tools, tests and prototypes, while a busy web app with many concurrent writers is better served by a server database such as PostgreSQL.

Mental model: SQL and values travel separately
  1. Prepare SQL with ? placeholders
  2. Pass the values separately in a tuple
  3. Constraints check every row
  4. with conn: commits or rolls back

SQL is code and values are data; never mix the two in one string.

General pattern

python
conn = sqlite3.connect("file.db")          # or ":memory:"
conn.row_factory = sqlite3.Row

with conn:                                  # commit on success, rollback on error
    cur = conn.execute("INSERT INTO table_name (col_a, col_b) VALUES (?, ?)",
                       (value_a, value_b))
    new_id = cur.lastrowid

rows = conn.execute("SELECT col_a FROM table_name WHERE col_b = ?", (value,)).fetchall()
conn.close()

Put changes (INSERT, UPDATE, DELETE) inside with conn: and pass every value through a placeholder. Even a single value needs a tuple with a trailing comma: (value,).

Example: CRUD and a rollback on a users table

The example uses a :memory: database so no file is left on disk. We create a table, insert three users, read, update and delete, then watch a duplicate-name INSERT break the UNIQUE constraint and roll back the whole block. Notice that "Zaw", inserted successfully one line earlier, is gone at the end.

sqlite_crud.py
import sqlite3

# ":memory:" = a throwaway database in RAM; use "app.db" for a real file
conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row  # rows can be read by column name
print("Database connected")

conn.execute("""
    CREATE TABLE users (
        id    INTEGER PRIMARY KEY,
        name  TEXT NOT NULL UNIQUE,
        age   INTEGER CHECK (age >= 0)
    )
""")
print("Table 'users' created")

# INSERT: always pass values as parameters, never with f-strings
with conn:  # commits on success, rolls back on an exception
    conn.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Sai", 25))
    conn.executemany("INSERT INTO users (name, age) VALUES (?, ?)",
                     [("Aye", 30), ("Mya", 22)])
print("Data inserted")

# SELECT
for row in conn.execute("SELECT id, name, age FROM users ORDER BY id"):
    print(f"ID: {row['id']}, Name: {row['name']}, Age: {row['age']}")

# UPDATE and DELETE report how many rows they touched
with conn:
    cur = conn.execute("UPDATE users SET age = ? WHERE name = ?", (26, "Sai"))
    print("Rows updated:", cur.rowcount)
    cur = conn.execute("DELETE FROM users WHERE name = ?", ("Aye",))
    print("Rows deleted:", cur.rowcount)

# A constraint violation rolls the whole block back
try:
    with conn:
        conn.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Zaw", 40))
        conn.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Sai", 99))
except sqlite3.IntegrityError as e:
    print("Rolled back:", e)

count = conn.execute("SELECT COUNT(*) FROM users").fetchone()[0]
print("Users left:", count)
conn.close()
print("Connection closed")

Code breakdown

  1. Connectconn = sqlite3.connect(":memory:")

    A database in RAM. Pass a file path such as "app.db" and the rest of the code works unchanged, but the data survives after the program ends.

  2. Constraintsname TEXT NOT NULL UNIQUE,

    The database itself rejects a missing name or a duplicate one. id INTEGER PRIMARY KEY hands out ids 1, 2, 3 automatically.

  3. Parametersconn.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Sai", 25))

    The two ? placeholders match the tuple's two values in order. executemany() takes a list of such tuples and runs once per row.

  4. rowcountcur = conn.execute("UPDATE users SET age = ? WHERE name = ?", (26, "Sai"))

    cur.rowcount is 1, confirming that one row changed. A 0 would mean no row matched the WHERE clause, which is not an error.

  5. Rollbackexcept sqlite3.IntegrityError as e:

    Inserting "Sai" again violates UNIQUE, so with conn: rolls back and re-raises the exception. That is why Users left is 2.

You should see
Database connected
Table 'users' created
Data inserted
ID: 1, Name: Sai, Age: 25
ID: 2, Name: Aye, Age: 30
ID: 3, Name: Mya, Age: 22
Rows updated: 1
Rows deleted: 1
Rolled back: UNIQUE constraint failed: users.name
Users left: 2
Connection closed

Named placeholders, indexes and query plans

Placeholders in the :name style take a dict, which prevents order mix-ups in INSERTs with many columns. EXPLAIN QUERY PLAN shows how SQLite will run a query: before the index exists it SCANs every row, and afterwards it reports SEARCH ... USING INDEX. The exact wording of the plan can differ slightly between SQLite versions.

query_plan.py
import sqlite3

conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)")
conn.executemany("INSERT INTO users (name, age) VALUES (:name, :age)",
                 [{"name": "Sai", "age": 25}, {"name": "Aye", "age": 30}])

query = "SELECT name FROM users WHERE age > ?"
print([row[3] for row in conn.execute("EXPLAIN QUERY PLAN " + query, (20,))])
conn.execute("CREATE INDEX idx_users_age ON users (age)")
print([row[3] for row in conn.execute("EXPLAIN QUERY PLAN " + query, (20,))])
print(conn.execute(query, (26,)).fetchall())
conn.close()

In real projects

Where this shows up in real projects

SQLite is everywhere: settings and caches in desktop apps, local data for CLI tools, sensor logs on IoT devices, and CSV files you want to query with SQL during data analysis. A new Django project uses SQLite as its default database, and test suites use :memory: databases so each test runs fast and starts clean.

In production you design tables with constraints, add indexes on frequently searched columns and confirm them with EXPLAIN QUERY PLAN, and keep related changes in one transaction, for example reducing stock and recording the sale together. Change the schema only through migration scripts, and never hand-edit a production database file or change it without a backup. Python's connection.backup() method can copy a live database safely.

Common mistakes

Common mistakes

1. Building SQL with f-strings or %

Every time user input is glued into an SQL string you risk SQL injection, and names containing quotes, such as O'Brien, break the syntax as well. Pass every value through a ? or :name placeholder.

2. Passing a single value without a comma

("Aye") is just a string, not a tuple. sqlite3 treats it as a sequence of characters and raises ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 3 supplied. Write ("Aye",) with a comma.

3. Forgetting to commit, or expecting with conn: to close

Closing without a commit throws the changes away. with conn: handles commit and rollback but leaves the connection open, so call conn.close() when you are done or wrap the connection in contextlib.closing().

4. Trying to pass a table name as a placeholder

SELECT * FROM ? is an error, because placeholders stand for values only. If a table or column name must vary, check it against an allow-list of permitted names before putting it into the string.

Best practices

Best practices

  • Write business rules not only in Python but also as NOT NULL, UNIQUE and CHECK constraints in the database.
  • Group changes that must happen together in one with conn: block, and never wait for user input inside it.
  • Keep database access in small functions such as setup() and sell(), which are easy to test against :memory:.
  • Name the columns you need instead of SELECT *, so a changed table does not silently break the code.

Mini challenge

Mini challenge: a stock-selling transaction

Build a small shop database with a products table and a sales table, then write sell(), which reduces the stock and records the sale in a single transaction.

  • The products table has stock INTEGER NOT NULL CHECK (stock >= 0)
  • sell(conn, sku, qty) runs the UPDATE and the INSERT with parameters inside one with conn:
  • If stock is insufficient (IntegrityError), nothing changes and it returns a "not enough stock" message
  • For an unknown sku (rowcount == 0), it rolls back and returns an "unknown sku" message
shop_db.py
import sqlite3


def setup(conn):
    # TODO: CREATE TABLE products (sku TEXT PRIMARY KEY, name, stock with a CHECK)
    # TODO: CREATE TABLE sales (sku, qty)
    # TODO: insert ("TEA-01", "Green tea", 10) and ("CUP-02", "Cup", 2)
    ...


def sell(conn, sku, qty):
    # TODO: inside one "with conn:" block:
    #   UPDATE products SET stock = stock - ? WHERE sku = ?
    #   if rowcount == 0, raise LookupError so the block rolls back
    #   INSERT the sale
    # TODO: return "sold ...", "not enough stock for ..." or "unknown sku ..."
    ...


def stock_report(conn):
    # TODO: return the stock per sku and the number of sales rows
    ...


# TODO: sell 3 TEA-01, try 5 CUP-02, try a sku like "x' OR '1'='1", print the report

Expected: Four lines of output: sold 3 x TEA-01 not enough stock for CUP-02 unknown sku x' OR '1'='1 {'CUP-02': 2, 'TEA-01': 7} | sales rows: 1

Show hint

Breaking the CHECK constraint raises IntegrityError on the UPDATE line itself, so the sale INSERT is never reached. Any exception raised inside the with conn: block, LookupError included, triggers a rollback. dict(rows) turns a list of (sku, stock) tuples into a dict.

Show solution
shop_db.py
import sqlite3


def setup(conn):
    conn.execute("""
        CREATE TABLE products (
            sku   TEXT PRIMARY KEY,
            name  TEXT NOT NULL,
            stock INTEGER NOT NULL CHECK (stock >= 0)
        )
    """)
    conn.execute("CREATE TABLE sales (sku TEXT NOT NULL, qty INTEGER NOT NULL)")
    with conn:
        conn.executemany("INSERT INTO products VALUES (?, ?, ?)",
                         [("TEA-01", "Green tea", 10), ("CUP-02", "Cup", 2)])


def sell(conn, sku, qty):
    try:
        with conn:
            cur = conn.execute("UPDATE products SET stock = stock - ? WHERE sku = ?",
                               (qty, sku))
            if cur.rowcount == 0:
                raise LookupError(f"unknown sku {sku}")
            conn.execute("INSERT INTO sales (sku, qty) VALUES (?, ?)", (sku, qty))
        return f"sold {qty} x {sku}"
    except sqlite3.IntegrityError:
        return f"not enough stock for {sku}"
    except LookupError as e:
        return str(e)


def stock_report(conn):
    rows = conn.execute("SELECT sku, stock FROM products ORDER BY sku").fetchall()
    sales = conn.execute("SELECT COUNT(*) FROM sales").fetchone()[0]
    return f"{dict(rows)} | sales rows: {sales}"


conn = sqlite3.connect(":memory:")
setup(conn)
print(sell(conn, "TEA-01", 3))
print(sell(conn, "CUP-02", 5))
print(sell(conn, "x' OR '1'='1", 1))
print(stock_report(conn))
conn.close()

Quick quiz 1 / 3

What happens when you run conn.execute("DELETE FROM users WHERE name = ?", ("Aye"))?

Quick quiz 2 / 3

Both INSERTs inside a with conn: block succeed and the block ends. What state is the connection in now?

Quick quiz 3 / 3

Which conn.execute(...) call safely searches by a name the user typed?

What to remember

  • sqlite3 ships with Python; start with connect("app.db") or connect(":memory:").
  • Pass every value through a ? or :name placeholder, and write a single value as (value,).
  • NOT NULL, UNIQUE and CHECK constraints reject bad data with IntegrityError.
  • with conn: commits or rolls back, but you still close the connection with conn.close().

Python Standard Library — sqlite3 — Python Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.