Databases with SQLite · 10 / 15 Exercise Medium

Safe search

Objective

Create a Python program that searches users by part of their name with LIKE without concatenating text into the SQL: always use ? parameters. That way texts with quotes or SQL code cause no problems (SQL injection). Use an in-memory database with the sqlite3 module (sqlite3.connect(":memory:")).

Instructions

  • Create the table users with the column name. Read n names (one per line) and insert them.
  • Read an integer q and then q search texts (the whole line, it may contain spaces and quotes).
  • For each text look for the names that contain it: WHERE name LIKE '%' || ? || '%', passing the text as a parameter. Sort by name.
  • Show Matches for "text": k and then each name found as - name (with two spaces at the start).
Input
4
Ana
anabel
Juan
Maria
3
an
zz
o' OR '1'='1
Output
Matches for "an": 3
  - Ana
  - Juan
  - anabel
Matches for "zz": 0
Matches for "o' OR '1'='1": 0

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise