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:
- Create a
bookstable with a few rows using a.sqlfile. - Write a script that connects and prints every title.
- 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:
- Ask for a title and author, then INSERT them.
- Commit, then re-run week 1's script to see the new row.
- Add
NOT NULLto 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:
- List books with their ids.
- Ask for an id and a new title; UPDATE that row only.
- Ask for an id and DELETE that row after a confirmation prompt.
- 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:
- Build a loop: list, add, edit, delete, quit.
- Catch
sqlite3.IntegrityErrorand show a friendly message. - 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
| Week | Operation | Key habit |
|---|---|---|
| 1 | Read | Placeholders |
| 2 | Create | Commit |
| 3 | Update and delete | Always WHERE |
| 4 | All four | Errors 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.