🐍 Python for Everyone

← Back to the quiz

Chapter 21 Exercises 40 min, hands-on

Exercises: Working with Databases

How to run these Download starter.py below, then run python3 starter.py from inside the folder you saved it in. Every "database" here is a FakeConnection/FakeCursor or FakeCollection class standing in for a real mysql-connector-python/pymongo object — no live database or installed driver is needed.

1 Querying with a parameterized WHERE clause

Get a connection and cursor from FakeConnection(STUDENTS_TABLE), run a parameterized query for students with grade > 80, and print each matching name.

2 fetchone()

Run a parameterized query matching one student by name and print cursor.fetchone().

3 Building an unsafe query

Write build_unsafe_query(name) and call it with a malicious input to see how SQL injection changes a query's meaning — this only builds and prints the string, it's never executed against anything.

4 The parameterized fix

Write build_safe_query_and_params(name) — the same malicious input, now harmless, kept as data instead of glued into the SQL string.

5 MongoDB insert_one and find

Insert two documents into a FakeCollection() and print everything currently stored.

6 MongoDB update_one

Update one document's grade field using {"$set": ...} and confirm the change.

7 MongoDB delete_one

Delete one document and confirm only the other one remains.

8 Cloud credentials via environment variables

Write build_connection_info() that reads connection details from os.environ instead of hardcoding them.

🐞 Task 9 — Debug the Code

This is supposed to look up "Ben Osei" by name, but it builds the SQL string with an f-string instead of a parameterized query — the exact SQL injection risk from Sub-topic 4. It also returns the wrong row here, since the fake cursor doesn't recognize the f-string's shape and falls back to returning every row. Find and fix it.

buggy_unsafe_lookup.py
def unsafe_lookup(cursor, name):
    sql = f"SELECT * FROM students WHERE name = '{name}'"
    cursor.execute(sql)
    return cursor.fetchone()


debug_cursor = FakeConnection(STUDENTS_TABLE).cursor()
print(unsafe_lookup(debug_cursor, "Ben Osei"))
← Back to Quiz Practice Bank →