Python Intermediate - Lesson 12 - Working with SQLite Databases

Python Intermediate · Lesson 12

Working with SQLite Databases

A database stores structured information so you can find and update it later. Python includes sqlite3, a built-in library for working with SQLite databases, so there is no extra package to install for this lesson.

By the end, you can: connect to a SQLite database, create a table, safely insert values with placeholders, query rows, and calculate a summary.
Important habit: use placeholders like ? for values in SQL queries. Do not build SQL by joining user input into a string. Also remember that a connection's context manager handles a transaction, but does not close the connection for you.

1. Connect to a database

sqlite3.connect() opens a database file or creates it if it does not exist. Use :memory: for a temporary database that disappears when the connection closes.

import sqlite3

connection = sqlite3.connect("practice.db")
print("Connected to practice.db")
connection.close()

2. Create a table

A table has named columns with data types. Use CREATE TABLE IF NOT EXISTS so the setup can run again without an error if the table is already there.

import sqlite3

connection = sqlite3.connect("practice.db")

connection.execute("""
    CREATE TABLE IF NOT EXISTS books (
        id INTEGER PRIMARY KEY,
        title TEXT NOT NULL,
        pages INTEGER NOT NULL
    )
""")
connection.commit()
connection.close()

PRIMARY KEY identifies each row. NOT NULL means that a value must be supplied for that column.

3. Insert values safely

Put ? placeholders in the SQL and pass the values separately as a tuple. SQLite treats these as data, not as SQL instructions.

import sqlite3

connection = sqlite3.connect("practice.db")
connection.execute("""
    INSERT INTO books (title, pages)
    VALUES (?, ?)
""", ("The Quiet Robot", 215))
connection.commit()
connection.close()
Why placeholders? They keep values separate from query structure and help prevent SQL injection bugs. Use one placeholder for each value; do not put quotes around the ?.

4. Query rows

execute() runs a query. fetchall() returns the rows it found as a list of tuples.

import sqlite3

connection = sqlite3.connect("practice.db")
rows = connection.execute(
    "SELECT title, pages FROM books ORDER BY title"
).fetchall()

for title, pages in rows:
    print(f"{title}: {pages} pages")

connection.close()

Use fetchone() when you need one row, or loop over the cursor when you want to process rows one at a time.

5. Use a connection context manager

The connection context manager commits a successful transaction and rolls back changes if an error occurs inside the block. Close the connection separately when finished.

import sqlite3

connection = sqlite3.connect("practice.db")
try:
    with connection:
        connection.execute(
            "INSERT INTO books (title, pages) VALUES (?, ?)",
            ("Cloud Atlas Notes", 96)
        )
finally:
    connection.close()

6. Calculate a summary in SQL

SQL can calculate totals. SUM() returns None if there are no matching values, so provide a default when needed.

row = connection.execute(
    "SELECT COUNT(*), COALESCE(SUM(pages), 0) FROM books"
).fetchone()

book_count, total_pages = row
print(f"{book_count} books, {total_pages} pages total")

Hands-on exercises

  1. Create a table named tasks with an integer primary key, a non-empty text description, and a completion status.
  2. Insert a task using placeholders, then select and print all task descriptions.
Show Solution & Common Mistakes

Exercise 1 — one possible solution

import sqlite3

connection = sqlite3.connect("tasks_practice.db")
connection.execute("""
    CREATE TABLE IF NOT EXISTS tasks (
        id INTEGER PRIMARY KEY,
        description TEXT NOT NULL,
        is_done INTEGER NOT NULL DEFAULT 0
    )
""")
connection.commit()
connection.close()

Exercise 2 — one possible solution

import sqlite3

connection = sqlite3.connect("tasks_practice.db")
connection.execute(
    "INSERT INTO tasks (description) VALUES (?)",
    ("Review database notes",)
)
connection.commit()

for (description,) in connection.execute(
    "SELECT description FROM tasks ORDER BY id"
):
    print(description)

connection.close()

Common mistakes:

  • Forgetting the comma in a one-item tuple: ("A task",) is a tuple; ("A task") is just a string.
  • Forgetting to commit changes when not using the connection context manager.
  • Concatenating user input into SQL instead of using placeholders.
  • Assuming with connection: closes the connection. It manages transaction completion; call close() separately.
  • Expecting a new database each run. connect("name.db") reopens the same file, so its saved rows remain.

Quick quiz

Choose an answer, then select Check answer.

1. How should a value be added to a parameterized SQLite query?

2. What does with connection: manage?

3. Do you need to install a package to use Python's sqlite3?

Mini-project: Study Session Database

Make a small command-line program that saves study sessions, lists them, and displays a total number of minutes. The program should keep its database between runs.

Requirements:

  • Create a database file named study_sessions.db.
  • Create a table with an ID, topic, positive number of minutes, and timestamp.
  • Offer a menu to add a session, list sessions, show a total, or quit.
  • Validate user input and use placeholders for SQL values.
  • Close the database connection when the program ends.

Hints: store each session with a parameterized INSERT. Use ORDER BY id DESC to show recent entries first, and COALESCE(SUM(minutes), 0) for an empty database total.

Show Full Project Solution
import sqlite3
from pathlib import Path

DATABASE = Path("study_sessions.db")


def create_table(connection):
    connection.execute("""
        CREATE TABLE IF NOT EXISTS sessions (
            id INTEGER PRIMARY KEY,
            topic TEXT NOT NULL,
            minutes INTEGER NOT NULL CHECK (minutes > 0),
            logged_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
        )
    """)
    connection.commit()


def add_session(connection):
    topic = input("Study topic: ").strip()
    if not topic:
        print("Topic cannot be blank.")
        return

    raw_minutes = input("Minutes studied: ").strip()
    try:
        minutes = int(raw_minutes)
    except ValueError:
        print("Enter a whole number of minutes.")
        return

    if minutes <= 0:
        print("Minutes must be greater than zero.")
        return

    with connection:
        connection.execute(
            "INSERT INTO sessions (topic, minutes) VALUES (?, ?)",
            (topic, minutes)
        )
    print("Session saved.")


def list_sessions(connection):
    rows = connection.execute("""
        SELECT topic, minutes, logged_at
        FROM sessions
        ORDER BY id DESC
    """).fetchall()

    if not rows:
        print("No study sessions saved yet.")
        return

    for topic, minutes, logged_at in rows:
        print(f"{logged_at} | {topic} | {minutes} minutes")


def show_total(connection):
    row = connection.execute(
        "SELECT COALESCE(SUM(minutes), 0) FROM sessions"
    ).fetchone()
    print(f"Total study time: {row[0]} minutes")


def main():
    connection = sqlite3.connect(DATABASE)
    try:
        create_table(connection)

        while True:
            print("\\nStudy Session Tracker")
            print("1. Add a session")
            print("2. List sessions")
            print("3. Show total minutes")
            print("4. Quit")
            choice = input("Choose 1-4: ").strip()

            if choice == "1":
                add_session(connection)
            elif choice == "2":
                list_sessions(connection)
            elif choice == "3":
                show_total(connection)
            elif choice == "4":
                print("Goodbye.")
                break
            else:
                print("Choose 1, 2, 3, or 4.")
    finally:
        connection.close()


if __name__ == "__main__":
    main()

Run the script from a practice folder. The first run creates the database and table; later runs reopen the same database, so saved sessions remain. To reset your practice data, close the program and remove study_sessions.db yourself.

Posts les plus consultés de ce blog

Python Programming Exercises with Solutions - Complete Beginner's Guide

Python Basics - Capstone - Study Sprint Tracker

Python Intermediate - Lesson 10 - Working with Excel Spreadsheets