1.Store and query data with SQLite
IntermediateUsing the built-in sqlite3 module and an in-memory database, create a products table, insert three products with a parameterised query, then print the products cheaper than 1000, cheapest first.
Show hint
Use ? placeholders and pass the values separately: cur.execute("... WHERE price < ?", (1000,)). executemany inserts a list of rows.
Show solution
import sqlite3
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute("CREATE TABLE products (name TEXT, price INTEGER)")
cur.executemany(
"INSERT INTO products (name, price) VALUES (?, ?)",
[("Notebook", 60), ("Headphones", 2500), ("Pen Set", 250)],
)
conn.commit()
for name, price in cur.execute(
"SELECT name, price FROM products WHERE price < ? ORDER BY price", (1000,)
):
print(name, price)
conn.close()Notebook 60
Pen Set 250Never build SQL by joining strings with user input (for example f"... WHERE name = '{name}'"). Placeholders keep the values separate from the SQL, which prevents SQL injection.