Run a SQL query from a Python program, loop over the rows it returns, and pass values in safely with ?.
Every app that saves anything has a program in the middle: it asks the database, then does something with the answer.
What you should already know:
Print text· Show text on the screen with print, and join pieces of text into one line with +.
Lists· Keep many values under one name, pick one by its place, and count them with len.
Until now you typed SQL straight into the database. An app does it from a program. Python's sqlite3 module talks to the same SQLite you have been using.
The first lines of every program here set up the music library for you. Copy them as they are. The part to read is the loop at the bottom.
How this lesson works: Predict, Run, Investigate, Modify, Make
Predict: Read the code and say what it will do before you run anything. A wrong guess is fine: it shows you what to look for.
Run: Run it and compare the result with your prediction.
Investigate: Trace how each line of code connects to what you see.
Modify: Change the code on purpose and check the result.
Make: Build something new using what you have learned. Expect a few tries; that is normal.
Make your prediction first. Help opens once you've locked it in.
PredictRead the code and say what it will do before you run anything. A wrong guess is fine: it shows you what to look for.
Predict
lesson.py
import sqlite3
conn = sqlite3.connect(":memory:")
conn.executescript(open("music.sql").read())
for row inconn.execute("SELECT title, plays FROM songs WHERE genre = 'pop'"):
print(row)
RunRun it and compare the result with your prediction.
Run
Run it and compare with your prediction.
Part
What it does
conn = sqlite3.connect(":memory:")
Opens a database held in memory
conn.executescript(open("music.sql").read())
Fills it with the music library (copy this)
conn.execute("SELECT ...")
Sends a SQL query and gets the rows back
for row in ...
Goes through the rows one at a time
lesson.py
import sqlite3
conn = sqlite3.connect(":memory:")
conn.executescript(open("music.sql").read())
for row inconn.execute("SELECT title, plays FROM songs WHERE genre = 'pop'"):
print(row)
Try it yourselfYour edits are saved in this browser.
InvestigateTrace how each line of code connects to what you see.
Investigate
lesson.py
import sqlite3
conn = sqlite3.connect(":memory:")
conn.executescript(open("music.sql").read())
for row inconn.execute("SELECT title, plays FROM songs WHERE genre = 'pop'"):
print(row[0], "has", row[1], "plays")
Count along the columns.
Where does the user's text end up?
ModifyChange the code on purpose and check the result.
Modify
Change the program so it prints the title and length in seconds of every rock song.
Try it yourselfYour edits are saved in this browser.
I can run a query from a Python program and loop over the rows.
I can take a row apart by position.
I can pass a typed value into a query with ?.
Running the lesson
Predict: students may expect only titles. The pair shows that a row is a whole row, just like the results table.
Run: the first four lines are copied, not explained. Say so, so nobody gets stuck on open().read().
Investigate: keep the placeholder idea at the level of 'text typed by a person must never become part of the SQL'.
Make: the query string stays fixed and the genre goes in separately.
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
FileNotFoundError: music.sql Ask: Did the program load this lesson's files? Fix: Use the Get this lesson's files button on the playground, then run again.
A row prints with brackets and quotes. Ask: What does row hold? Fix: row is a pair. Print row[0] to get just the title.
sqlite3.ProgrammingError about the number of bindings Ask: How many ? are in the query and how many values are passed? Fix: One value for each ?, in a pair of brackets with a comma, such as (genre,).
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.
Where it leads
Next: a small web app that keeps its data in a database (Flask with a database).
What each step is for
Investigate: Each row arrives as a pair you can take apart by position. The SQL does the finding; Python does what you want with the answer.