Code

Bind the Visitor's Name

A visitor named O'Malley arrives at the guild desk. The old search program crashes. Pip frowns: "That apostrophe broke our SQL!"

Never paste values into SQL

It is tempting to build SQL with an f-string:

sql = f"SELECT * FROM members WHERE name = '{name}'"

This has two big problems:

  1. It breaks. For O'Malley, SQL sees the apostrophe as the end of the text. You get sqlite3.OperationalError.
  2. It's dangerous. Someone could type the name x' OR '1'='1. The query becomes WHERE name = 'x' OR '1'='1', which is true for every row. Tricking a program into running your SQL is called SQL injection. Real attackers use it to read or wipe whole databases.

Use ? placeholders

row = conn.execute(
    "SELECT * FROM members WHERE name = ?",
    (name,),
).fetchone()

Each ? is an empty slot. Pass the values as a tuple in the second argument, one per ?, in order. sqlite3 sends them separately from the SQL, so a value can never turn into SQL code. Apostrophes just work. (name,) needs the comma: it makes a one-item tuple.

This is the only safe way to put values into SQL. Placeholders work for values, not for table or column names.

Remember: fetchone() returns the first row, or None if nothing matched.

Assignment

  1. Fix find_member(conn, name). Use a ? placeholder (no f-strings). Return the member's row (name, island, coins), or None if there is no such member.
  2. Write add_member(conn, name, island, coins). It inserts one row using three ? placeholders.

The program should print ("O'Malley", 'Fog Reach', 30) and then None (the sneaky name matches nobody).