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

Free lesson

OS 6.3 (2 of 3): Connecting code to a database

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

55 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

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.
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 in a query where a value goes. The value is sent separately.
CommitSave your changes 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.

Code, connection and database

flowchart LR
  app[Your program] -->|1 open a connection with the details| conn((Connection))
  conn -->|2 send a query| db[(Database)]
  db -->|3 send the rows back| conn
  conn -->|4 use the rows| app
  app -->|5 close the connection| conn

Check: the words

Have a go

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

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.

Connect, add a row, read it back

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.

Make a free account to save your work and track your progress.

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.

A placeholder stops the attack

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

Make a free account to save your work and track your progress.

Match each word to its meaning

Have a go

Loading…

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

Network resources and your tools

A real database often runs on another computer. Your code reaches it over the network (computers joined together). Your editor can help. Most editors have a database tool. You add a data source: the server name, the port, your username, your password and the database name. You press Test Connection. If it works, you can look at the tables and run queries before you write any code.

Check: your editor

Have a go

Check: your editor

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

Write a connection card

The lab has a MySQL database. Press Start and open the lab page. It tells you how to reach the database. Write a connection card with four lines: the server name, the port, the database name, and the username. Do not write the password in your work: write where you would keep it in a real project. Then open phpMyAdmin and look at the products table. For each of Create, Read, Update and Delete, write what it would do to that table, with one SQL line each.

A teacher marks this in a college. Nothing you write here is kept: it goes when you leave the page.

Make a free account to save your work, or press Start lab to work through the whole lesson.

Write the four CRUD jobs in Python

Finish five functions that use a database connection. make_table creates the table and the other four are Create, Read, Update and Delete. Use ? placeholders in every query. The hidden tests also try a name with an apostrophe, and a name that is an injection attack. Press Run Tests.

Code: python
def make_table(conn):
    # Make a table called players with three columns:
    # id (whole number, primary key), name (text) and points (whole number).
    pass


def add_player(conn, name, points):
    # Add one row. Use ? placeholders, never join the text yourself.
    pass


def get_points(conn, name):
    # Give back the points of the player with this name, or None if there is no such player.
    return None


def update_points(conn, name, points):
    # Change the points of that player.
    pass


def delete_player(conn, name):
    # Remove that player.
    pass

Make a free account to save your work, or press Start lab to work through the whole lesson.

Query the top players

The table players has the columns name, team and points. Write a query that gives the names of players with more than 10 points, the highest points first. Show only the name column.

Code: sql
SELECT * FROM players;

Make a free account to save your work, or press Start lab to work through the whole lesson.

Exit quiz

Have a go

Exit quiz

6 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

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.