← Teacher guide

Ask the database from Python

Students run SQL from Python with sqlite3, loop over the rows, take a row apart by position and pass a value in with ?.

SQL and databases · SQL from Python · about 30 minutes · Open the student lesson

Classroom resources

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.

Students will be able to

Timing

Predict and Run 8 min · Investigate 8 min · Modify and Make 14 min

Running the lesson

  1. Predict: students may expect only titles. The pair shows that a row is a whole row, just like the results table.
  2. Run: the first four lines are copied, not explained. Say so, so nobody gets stuck on open().read().
  3. Investigate: keep the placeholder idea at the level of 'text typed by a person must never become part of the SQL'.
  4. Make: the query string stays fixed and the genre goes in separately.

In class

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.

The hard part (on purpose)

Moving between the two languages. Say which one each line is written in: the quoted part is SQL, the rest is Python.

When students get stuck

What you will seeA question to askThe fix
FileNotFoundError: music.sqlDid 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 bindingsHow 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,).

Answers to the checks

  1. Predict: Four songs are pop. What will the loop print?
    Four lines, each a pair. conn.execute gives back the rows, and each row is a (title, plays) pair, just like a row in the results table.
  2. Take a row apart: In `for row in conn.execute("SELECT title, plays FROM songs")`, what is row[1]?
    The plays of that song
    Positions count from 0 along the SELECT's columns: title is row[0], plays is row[1].
  3. A safer way: A program asks the user for a genre and joins it into the query text with +. What can go wrong?
    A quote in it can break or change the query
    A genre containing a quote can break the query, or change what it does. The typed text becomes part of the SQL. A ? placeholder passes the value separately, so it is always treated as a value and never as SQL.

Solutions

One possible solution for each task. Other correct programs are fine.

Modify

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])

Make

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 and support

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.

Exit ticket

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.

What each step is for

Where it leads

Next: a small web app that keeps its data in a database (Flask with a database).