← SQL and databases

Ask the database from Python

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.

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
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 in conn.execute("SELECT title, plays FROM songs WHERE genre = 'pop'"):
    print(row)
Four songs are pop. What will the loop print?

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 in conn.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 in conn.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?

In `for row in conn.execute("SELECT title, plays FROM songs")`, what is row[1]?

A program asks the user for a genre and joins it into the query text with +. What can go wrong?

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.
Build up to it
Which query text finds the soul songs?

Need a hint?

Before a hint: what kind of stuck is this? Try a strategy first

Change pop to rock in the query, and plays to seconds.

Another hint

SELECT title, seconds FROM songs WHERE genre = 'rock'

Print the title and length of every rock song.

    Run your program. This ticks when your code does all of the above.

    MakeBuild something new using what you have learned. Expect a few tries; that is normal.

    Make

    Make a tiny song finder. Ask the user for a genre, then print the title of every song in it. Pass the genre in with ?.

    Try it yourselfYour edits are saved in this browser.
    Need a hint?

    Before a hint: what kind of stuck is this? Try a strategy first

    Ask with input(), then pass the answer in as (genre,) after the query.

    Another hint

    conn.execute("SELECT title FROM songs WHERE genre = ?", (genre,))

    Ask for a genre and print its titles, passing the genre in with ?.

      Run your program. This ticks when your code does all of the above.

      Now you can
      Finished the course?Go over it: SQL and databases recapEvery idea in one place, to check you've got it.You reached the endBack to SQL and databases
      For teachers

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

      Open the teacher guide: answers, solutions, slides and a worksheet.

      Students will be able to

      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.

      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

      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