Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Preview

Connecting code to a database

This is the first page of the lesson. Read it and have a go at the activities. The rest is in the full lesson.

55 minutes

The leaderboard that forgets

You write a game. It keeps the scores in a list inside the program. You close the game. The scores are gone.

A program forgets everything when it stops. To keep data, the program must save it in a safe place. The usual place is a database (an organised store of data).

Today your code connects to one, and reads, adds, changes and deletes data.

Key words

WordWhat it means
DatabaseAn organised store of data that programs can search and change.
Data sourceAny place your program gets data from, such as a database file.
ConnectionAn open link between your program and the database.
ParameterAn extra setting you give when you open a connection.
CredentialsThe username and password that prove who you are.
QueryA question or an instruction you send to a database, written in SQL.
PlaceholderA mark such as ? in a query. The real value is sent separately.
CommitSave the changes you made to the database, so they stay.
SQL injectionAn attack where a user types SQL as their input and changes your query.
CRUDCreate, Read, Update, Delete: the four things a program does with data.

The cells students fill in are left blank in this preview.

Quick check: the words

Have a go

Quick check: the words

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Your answers are marked here and are not kept. A college account keeps every student’s marks.

What a connection needs

PartWhat it isSQLite file exampleMySQL lab example
Database name or data sourceWhich data to openshop.dbshop
Server and portWhere the database runs. A file has noneNone: it is a filedb, port 3306
CredentialsUsername and passwordNone neededstudent and student
Optional parametersExtra settings, such as how many seconds to waittimeout=5 (wait 5 seconds)a time limit, or a secure connection

The cells students fill in are left blank in this preview.

Try it: connect, create, read

Code: python
import sqlite3

conn = sqlite3.connect(":memory:")   # a database that lives in memory
conn.execute("CREATE TABLE players (name TEXT, points INTEGER)")
conn.execute("INSERT INTO players VALUES (?, ?)", ("Aisha", 12))
conn.commit()

for row in conn.execute("SELECT name, points FROM players"):
    print(row)
conn.close()

# Add a second player and run again.

CRUD in SQL and in Python

JobSQLPython call
Create (store)INSERTconn.execute("INSERT ...", values)
Read (extract)SELECTconn.execute("SELECT ...").fetchall()
UpdateUPDATEconn.execute("UPDATE ...", values)
DeleteDELETEconn.execute("DELETE ...", values)

The cells students fill in are left blank in this preview.

Never join user text into a query

Suppose you build a query by joining the name a user typed. A user types x' OR '1'='1. The query now says: find a player named x, or any row where 1 equals 1. 1 always equals 1, so the query returns every player.

This is SQL injection. The fix is a placeholder. The query and the value travel separately, so the value can never become part of the query. This is called a prepared statement.

Try it: unsafe and safe

Code: python
import sqlite3

conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (name TEXT, secret TEXT)")
conn.execute("INSERT INTO users VALUES ('Aisha', 'cat'), ('Sam', 'dog')")

typed = "x' OR '1'='1"

unsafe = "SELECT * FROM users WHERE name = '" + typed + "'"
print("Unsafe:", conn.execute(unsafe).fetchall())

print("Safe:  ", conn.execute("SELECT * FROM users WHERE name = ?", (typed,)).fetchall())

The lesson goes on

8 more parts of this lesson are in the full curriculum, with the tasks, the final check and the labs. A college account gives your students all of it.