Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 15.6 — Databases from Python: sqlite3 and Beyond
Python · Example 2 of 2

A transaction that rolls back

The second transfer fails halfway. Because of with conn:, the first UPDATE is undone too.

Python can store data in a database through a driver. The built-in sqlite3 module needs no server; whatever the database, always pass values to SQL as parameters (placeholders), never by pasting text, and group changes in transactions so they succeed or fail together.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write find_user(conn, name) that returns the row for a name using a placeholder, or None if it does not exist.

02

Write add_user(conn, name, plan) that inserts a user inside with conn: and returns the new id (cursor.lastrowid).

03

Write count_by_plan(conn) returning a dictionary such as {'free': 2, 'pro': 1} using GROUP BY.

Explain it without notes

01

What is SQL injection and how do parameterised queries prevent it?

02

What is a transaction, and how does with conn: behave in sqlite3?

03

Why can you not use a placeholder for a table name, and what do you do instead?

04

What does row_factory = sqlite3.Row change?

05

A teammate builds a query with an f-string and says "it is only an internal tool". How do you respond?

A transaction that rolls back
Sign in to run this example in your browser.

Expected output

after good transfer: {'asha': 70, 'ben': 50}
rejected: CHECK constraint failed: balance >= 0
after failed transfer: {'asha': 70, 'ben': 50}
in a transaction? False