← Python Coding Track

Module 11AdvancedWeeks 8–9

Working with Databases

01

Learning outcomes

  • Store and query data persistently using a database
02

Core concepts

SQLite basicsSQL fundamentals (SELECT, INSERT, UPDATE, DELETE)Connecting Python to a database
03

Lessons

Module goal

Move beyond flat text files and learn to store, query and manage data using a real database — the standard approach in professional applications.

Lesson 1 of 5 · lecture

Why databases instead of flat files

Step 1 of 2

Every project so far has saved data using plain text files — the Contact Manager, the Expense Tracker. That works at small scale, but breaks down quickly as data grows or gets more complex.

  • Searching is slow and manual — finding one contact among 10,000 lines means reading the whole file every time
  • There's no structure enforcement — nothing stops a line saving with a missing field or the wrong field order
  • Relationships are hard to represent — connecting customers to devices to repair jobs has no natural expression in a text file
  • Multiple parts of a program writing to the same file at once risk corrupting it

A natural evolution

Text files were the right tool for Modules 6, 7 and 10 because the data and scale were simple. Databases become the right tool once an application needs to reliably search, filter and relate larger, structured sets of data — exactly where a repair-tracking business lives.

04

Guided labs

Lab — convert the Contact Manager to SQLite

  1. 1.Return to the Contact Manager from the Module 7 capstone (already strengthened with error handling in Module 8)
  2. 2.Create database.py with setup_database() that creates the contacts table if it doesn't exist
  3. 3.Replace load_contacts() and save_contacts() with add_contact(), get_all_contacts() and delete_contact()
  4. 4.Update main.py's menu loop to call the new database functions instead of the file-based ones
# database.py
import sqlite3

def setup_database():
    connection = sqlite3.connect("contacts.db")
    cursor = connection.cursor()
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS contacts (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            phone TEXT,
            email TEXT
        )
    """)
    connection.commit()
    connection.close()

def add_contact(name, phone, email):
    connection = sqlite3.connect("contacts.db")
    cursor = connection.cursor()
    cursor.execute(
        "INSERT INTO contacts (name, phone, email) VALUES (?, ?, ?)",
        (name, phone, email)
    )
    connection.commit()
    connection.close()

def get_all_contacts():
    connection = sqlite3.connect("contacts.db")
    cursor = connection.cursor()
    cursor.execute("SELECT name, phone, email FROM contacts")
    rows = cursor.fetchall()
    connection.close()
    return rows

def delete_contact(name):
    connection = sqlite3.connect("contacts.db")
    cursor = connection.cursor()
    cursor.execute("DELETE FROM contacts WHERE name = ?", (name,))
    connection.commit()
    connection.close()


# main.py
from database import setup_database, add_contact, get_all_contacts, delete_contact

setup_database()

while True:
    print("\n1. Add contact  2. View contacts  3. Delete contact  4. Exit")
    choice = input("Choose an option: ")

    if choice == "1":
        name = input("Name: ")
        phone = input("Phone: ")
        email = input("Email: ")
        add_contact(name, phone, email)

    elif choice == "2":
        for name, phone, email in get_all_contacts():
            print(f"{name} | {phone} | {email}")

    elif choice == "3":
        name = input("Enter name to delete: ")
        delete_contact(name)

    elif choice == "4":
        break

    else:
        print("Invalid option, try again.")

Teaching point

Be able to explain why this scales better than the Module 7 text-file version — particularly around searching and structural reliability.

Success criteria

Contacts persist correctly in contacts.db between runs, can be added, viewed and deleted through the menu, and the learner can explain why the database approach scales better than the text-file version.

05

Knowledge Check

Question 1 of 6

Which of these is a genuine limitation of storing data in a plain text file that a database solves?

06

What you read

  • Why databases outperform flat files at scale
  • Core SQL syntax
  • Using sqlite3 in Python
07

What you understand

Key takeaways

  • Databases are the backbone of real applications
  • Data must be structured and queryable
08

Hands-on lab

Lab tasks

  1. 1.Convert the Contact Manager to use SQLite instead of a text file
09

Knowledge check

  • Write basic SQL queries
  • Identify correct database operations

Write your answers in your own notes before moving on — explaining a concept in your own words is the fastest way to find the gaps.

10

Mark progress