SQLite gives Python programs a lightweight relational database. Tables have columns and rows; parameterised statements help separate values from SQL commands. Practise inserting, selecting and updating sample records.
Watch out: Do not construct SQL queries by concatenating untrusted user input. Use placeholders with parameters.
Study this example, identify inputs and outputs, then trace the key variables. Run and adapt it in Python 3.
import sqlite3
with sqlite3.connect(':memory:') as connection:
connection.execute('CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT NOT NULL, author TEXT NOT NULL)')
books = [('Algorithms Made Clear', 'A. Writer'), ('Learning Python', 'B. Author')]
connection.executemany('INSERT INTO books(title, author) VALUES (?, ?)', books)
rows = connection.execute('SELECT title FROM books ORDER BY title').fetchall()
2 · Independent programming challenge
Create a table, insert records using parameterised SQL and query sorted results. Download the starter, design your solution, and add tests before revealing the answer.
Stretch task: investigate time/space complexity or data validation, then write an evaluation of your approach.
Show reference solution after attempting the task
import sqlite3
with sqlite3.connect(':memory:') as connection:
connection.execute('CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT NOT NULL, author TEXT NOT NULL)')
books = [('Algorithms Made Clear', 'A. Writer'), ('Learning Python', 'B. Author')]
connection.executemany('INSERT INTO books(title, author) VALUES (?, ?)', books)
rows = connection.execute('SELECT title FROM books ORDER BY title').fetchall()
assert rows == [('Algorithms Made Clear',), ('Learning Python',)]
print(rows)
3 · Debug and explain
Change one boundary condition in the starter or reference program. Predict which test fails, then repair it and document why.
Concept check: Why use SQL placeholders instead of string concatenation?
Reveal explanation
Parameters keep data separate from SQL instructions and help prevent SQL injection.
4 · Assess your learning
Describe the algorithm or design in your own words; include a normal test, a boundary test and an invalid input. Compare your answers with the reference solution and record one improvement.
Separate table design from queries: decide the primary key and suitable field types before inserting records. Use parameterised queries for user-provided values and test foreign-key relationships deliberately.
Quick check: Why are parameterised SQL queries preferable to concatenating input into SQL strings?
Check: They keep input values separate from query syntax, reducing SQL injection risks.