Students run SQL from Python with sqlite3, loop over the rows, take a row apart by position and pass a value in with ?.
Open these in Waypoints Prepare with one click. To share a file another way, copy its address and paste it into Load URL, or download the file and import it. In Prepare, the worksheet's Teacher edition shows the answers; the student copy hides them.
Predict and Run 8 min · Investigate 8 min · Modify and Make 14 min
On the slides at these points. Students can do the whole lesson on their own; these are for the room. In the deck, the Run, Modify and Make slides have the live playground in them (the tutorial link is the backup), and the notes above are in each slide's speaker notes.
Show the loop. Students colour the SQL in one colour and the Python in another, then explain what each part sends or receives.
Moving between the two languages. Say which one each line is written in: the quoted part is SQL, the rest is Python.
| What you will see | A question to ask | The fix |
|---|---|---|
| FileNotFoundError: music.sql | Did the program load this lesson's files? | Use the Get this lesson's files button on the playground, then run again. |
| A row prints with brackets and quotes. | What does row hold? | row is a pair. Print row[0] to get just the title. |
| sqlite3.ProgrammingError about the number of bindings | How many ? are in the query and how many values are passed? | One value for each ?, in a pair of brackets with a comma, such as (genre,). |
One possible solution for each task. Other correct programs are fine.
import sqlite3
conn = sqlite3.connect(":memory:")
conn.executescript(open("music.sql").read())
for row in conn.execute("SELECT title, seconds FROM songs WHERE genre = 'rock'"):
print(row[0], row[1])
import sqlite3
conn = sqlite3.connect(":memory:")
conn.executescript(open("music.sql").read())
genre = input("Genre? ")
for row in conn.execute("SELECT title FROM songs WHERE genre = ?", (genre,)):
print(row[0])
Stretch: Let the user type a genre, then print the number of songs in it with COUNT(*).
Support: Give the loop and ask only for the query.
Why pass a typed genre with ? instead of joining it into the query with +?
So the typed text is always a value and can never change the SQL itself.
Next: a small web app that keeps its data in a database (Flask with a database).