
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 TABLEnames the columns and their types:TEXTfor words,INTEGERfor whole numbers.INSERT INTO ... VALUES (...)adds one row. Inside SQL, text goes in single quotes.SELECT * FROMreads 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():
- Connect to a new in-memory database.
- Create the table
memberswith the columnsname TEXT,island TEXTandcoins INTEGER. - Insert the three members shown (keep the values exactly).
- 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)]Fill in every ___ inside open_ledger():
- Connect to a new in-memory database.
- Create the table
memberswith the columnsname TEXT,island TEXTandcoins INTEGER. - Insert the three members shown (keep the values exactly).
- 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)]Press Run to try your code, then Check to test it.