Fill in

Open the Guild Database

Pip pushes open a dusty door. "The Guild Ledger! Every member, every coin. Let's make our own copy."

Tables, rows and columns

A database stores data in tables. A table looks like a spreadsheet. Each column has a name and a type. Each row is one record, like one guild member.

SQL (say "S-Q-L" or "sequel") is the language for talking to databases. Python's built-in sqlite3 module runs a whole SQL database inside your program.

import sqlite3

conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE lanterns (island TEXT, lit INTEGER)")
conn.execute("INSERT INTO lanterns VALUES ('Amber Isle', 3)")
rows = conn.execute("SELECT * FROM lanterns").fetchall()
print(rows)  # [('Amber Isle', 3)]
  • sqlite3.connect(":memory:") opens a brand-new database that lives in memory. It vanishes when the program ends. (A file name like "guild.db" would save it to disk instead.)
  • conn.execute(sql) runs one SQL statement.
  • CREATE TABLE names the columns and their types: TEXT for words, INTEGER for whole numbers.
  • INSERT INTO ... VALUES (...) adds one row. Inside SQL, text goes in single quotes.
  • SELECT * FROM reads every column. .fetchall() hands you the rows as a list.

Money is whole coins

The Guild stores money as whole coins in an INTEGER column, never as decimals. Floats are not exact (0.1 + 0.2 is 0.30000000000000004), and a ledger must be exact.

Pip tip: SQL keywords work in any case, but writing them in CAPITALS makes them easy to spot.

Assignment

Fill in every ___ inside open_ledger():

  1. Connect to a new in-memory database.
  2. Create the table members with the columns name TEXT, island TEXT and coins INTEGER.
  3. Insert the three members shown (keep the values exactly).
  4. Return the connection.

Then fill the last blank so the program prints every row:

[('Pip', 'Amber Isle', 40), ('Wren', 'Fog Reach', 25), ('Bram', 'Gull Rock', 0)]