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
| Word | What it means |
|---|---|
| Database | An organised store of data that programs can search and change. |
| Data source | Any place your program gets data from. |
| Connection | An open link between your program and the database. |
| Parameter | An extra setting you give when you open a connection. |
| Credentials | The username and password that prove who you are. |
| Query | A question or an instruction you send to a database, written in SQL. |
| Placeholder | A mark in a query where a value goes. The value is sent separately. |
| Commit | Save your changes to the database, so they stay. |
| SQL injection | An attack where a user types SQL as their input and changes your query. |
| CRUD | Create, 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 questionsWhat a connection needs
| Part | What it is | SQLite file example | MySQL lab example |
|---|---|---|---|
| Database name or data source | Which data to open | shop.db | shop |
| Server and port | Where the database runs. A file has none | None: it is a file | db, port 3306 |
| Credentials | Username and password | None needed | student and student |
| Optional parameters | Extra settings, such as how many seconds to wait | timeout=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
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
| Job | SQL | Python call |
|---|---|---|
| Create (store) | INSERT | conn.execute("INSERT ...", values) |
| Read (extract) | SELECT | conn.execute("SELECT ...").fetchall() |
| Update | UPDATE | conn.execute("UPDATE ...", values) |
| Delete | DELETE | conn.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
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 questionsWrite 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.
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.
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