A Four-Week Plan: CRUD From Your Own Code

Writing SQL in a database tool is one skill; doing the same from your own program is another. This four-week plan builds the second skill gradually. Each week has a goal, exercises, a way to check yourself and the pitfall to watch for. The examples use Python and SQLite.

Week 1: read

Goal: query a database from a script and print results.

Exercises:

  1. Create a books table with a few rows using a .sql file.
  2. Write a script that connects and prints every title.
  3. Add a filter: print books by one author, using a ? placeholder.
import sqlite3
conn = sqlite3.connect("books.db")
author = input("Author: ")
for (title,) in conn.execute("SELECT title FROM books WHERE author = ?", (author,)):
    print(title)
conn.close()

Check: typing an author with an apostrophe, such as O'Brien, still works. If it breaks, you are gluing strings.

Pitfall: forgetting the comma in (author,).

Week 2: create

Goal: add rows from your program.

Exercises:

  1. Ask for a title and author, then INSERT them.
  2. Commit, then re-run week 1's script to see the new row.
  3. Add NOT NULL to the title column and try inserting an empty title.

Check: after restarting the script, the new book is still there. If not, you forgot to commit.

Pitfall: building the INSERT with f-strings.

Week 3: update and delete

Goal: change and remove rows safely.

Exercises:

  1. List books with their ids.
  2. Ask for an id and a new title; UPDATE that row only.
  3. Ask for an id and DELETE that row after a confirmation prompt.
  4. Print how many rows were affected using the cursor's rowcount.

Check: entering an id that does not exist prints "0 rows affected" rather than crashing.

Pitfall: an UPDATE or DELETE without WHERE.

Week 4: put it together

Goal: a small menu program with all four operations.

Exercises:

  1. Build a loop: list, add, edit, delete, quit.
  2. Catch sqlite3.IntegrityError and show a friendly message.
  3. Wrap "move a book to another shelf" (two updates) in a transaction.

Check: you can explain, line by line, what each SQL statement in your program does.

Pitfall: opening a new connection for every menu choice; open once at the start.

Timeline summary

WeekOperationKey habit
1ReadPlaceholders
2CreateCommit
3Update and deleteAlways WHERE
4All fourErrors and transactions

Afterwards

Rewrite the menu program in a web framework, or in another language using the guide to drivers in four languages. The SQL barely changes; only the surrounding code does, which shows how transferable these skills are.

A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.

Related pages on this site