Python Master Course V2 — 083. SQLite with Python
SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · LESSON 083 OF 200 · MODULE 09 — DATABASES AND SQLITE
SQLite with Python
Study time: 70–100 minutes. Prerequisites: functions, exceptions, structured data and Lesson 82.
Video
Video not yet available. This section is reserved for a verified lesson video URL or embedded player.
Learning outcomes
Use sqlite3 connections and transactions. Explain the concept, trace a sample program, test a boundary condition and implement a small real-world solution.
Detailed explanation
SQLite is an embedded relational database stored in a file or memory. Parameterized queries and transaction boundaries help preserve consistency.
Engineering workflow: define the input and expected output, choose a representation, enforce constraints, implement the smallest useful operation, test success and failure paths, and document the result. Separate data acquisition from transformation and presentation. Avoid hidden global state and irreversible changes during practice.
Production considerations: validate external inputs, preserve recoverable source data, use explicit types, log failures without exposing secrets, and plan for malformed or missing records. As programs grow, modularize code into functions with clear contracts and add automated regression tests.
Understand and apply: SQLite with Python
A connection is both a database session and a resource
SQLite runs inside your program rather than in a separate database server. A file-backed connection stores committed data in the named database file. A :memory: connection creates a separate temporary database that disappears when that connection closes. Choose memory databases for isolated tests and file databases when you need to reopen the same data later.
Opening a connection, committing a transaction and closing a connection are three different operations. commit makes a successful transaction permanent; rollback abandons its uncommitted changes; close releases the connection’s resources. Do not assume close saves pending changes. The connection’s context manager controls a transaction under this lesson’s default sqlite3 transaction behavior, but it does not close the connection. Use contextlib.closing or a finally block for cleanup.
Python example
import sqlite3
from contextlib import closing
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
path = Path(folder) / "inventory.db"
with closing(sqlite3.connect(path)) as db:
db.execute("CREATE TABLE stock(sku TEXT NOT NULL UNIQUE, qty INTEGER NOT NULL CHECK(qty >= 0))")
with db:
db.execute("INSERT INTO stock VALUES (?, ?)", ("PEN", 10))
try:
with db:
db.execute("UPDATE stock SET qty = ? WHERE sku = ?", (7, "PEN"))
raise ValueError("cancel this change")
except ValueError:
print("rolled back")
with closing(sqlite3.connect(path)) as reopened:
print(reopened.execute("SELECT sku, qty FROM stock").fetchone())
Expected output
rolled back
('PEN', 10)
Trace the lifetimes from the outside inward. TemporaryDirectory gives the example a disposable destination. The first closing block owns a connection. The first with db block commits the initial stock. The next block changes it to seven, but the escaping ValueError causes rollback. The connection then closes. Reopening the same path sees ten, proving both the earlier commit and later rollback. Finally, the temporary directory is removed, so this demonstration intentionally leaves no permanent file.
Choose transaction settings deliberately
This course baseline uses Python 3.10-compatible sqlite3 calls and the default legacy transaction behavior. Python 3.12 and later also offer an autocommit setting. Do not copy examples mixing autocommit modes without reviewing their transaction boundaries: a with block is not universally a command to begin a new transaction. For explicit BEGIN examples later, the connection will use isolation_level=None and explicit commit/rollback consistently.
Handle IntegrityError when a valid SQL statement violates a constraint. OperationalError can indicate locking, an inaccessible path or another operational failure; it is not a reason to invent an empty inventory. Preserve the traceback during development and translate only expected errors at the application boundary. A database file path is relative to the process working directory unless made absolute, so print or document the resolved practice path when debugging a missing file.
Test persistence by committing, closing and reopening. Test rollback by failing after a first write and checking that the original value remains. Test independent in-memory connections to show that they do not share ordinary :memory: databases. For a real inventory application, keep the database outside a TemporaryDirectory and provide a backup policy rather than treating the disposable demonstration as a deployment layout.
Runnable Python example
Requires Python 3.10+. Save as lesson83.py, run with python lesson83.py or python3 lesson83.py. Examples use only the standard library.
import sqlite3
from contextlib import closing
with closing(sqlite3.connect(':memory:')) as db:
with db:
db.execute('CREATE TABLE items(id INTEGER PRIMARY KEY, name TEXT)')
db.execute('INSERT INTO items(name) VALUES (?)',('Pen',))
print(db.execute('SELECT COUNT(*) FROM items').fetchone()[0])
Expected output:
1
Walkthrough
Read the imports first, then identify the input and the operation that produces the result. Verify the expected output, change one input, predict the new result and rerun. Explain what should happen if the input is empty, invalid or unavailable.
Guided practical project
Scenario: Create a local inventory database with a documented schema.
- Specify the data schema and constraints in a small requirements table.
- Create a sample dataset with typical, boundary and invalid records.
- Implement separate functions for validation, transformation and reporting.
- Handle expected errors with informative messages.
- Write three automated tests and compare actual with expected results.
- Document execution, assumptions and limitations.
Acceptance criteria: reproducible output, safe handling of invalid data, no silent data loss, and clearly documented assumptions. The project is a guided assignment, not a claim that it has been executed here.
Common mistakes and debugging
- Using the wrong data type or assuming input is always valid.
- Failing to validate keys, fields, constraints or encodings.
- Hiding exceptions with a broad catch rather than identifying the cause.
- Changing important records without backups or transaction planning.
- Testing only normal inputs rather than empty and boundary cases.
When debugging, reproduce with a minimal example, inspect the traceback, compare values to the documented contract and add a regression test.
Practice with explained answers
Make a prediction before opening each answer. Then trace the example and explain the result in your own words.
Does with sqlite3.connect(…) automatically close the connection?
No. The connection context manager controls commit or rollback under the applicable transaction settings. Use closing(…) or an explicit finally block to release the connection.
Why does reopening the example return quantity 10 rather than 7?
The initial insert was committed. The later update was inside a transaction that exited with ValueError, so it was rolled back before closing.
Do two ordinary :memory: connections share tables?
No. Each creates its own in-memory database. Use the same connection or a deliberately configured shared approach; do not assume the filename-like string identifies shared persistent storage.
What is wrong with relying on close to commit?
Closing is resource cleanup, not an instruction to save a pending transaction. Commit explicitly on success and roll back on failure so the persistence contract is clear.
Why use a temporary directory in the teaching example?
It makes repeated runs isolated and removes practice files afterward. It is inappropriate when the goal is to retain a real application database between runs.
Mastery checkpoint
Reproduce the sample, explain each operation, complete the guided project and demonstrate at least three test cases. Learner progress is not account-synchronized by this page.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.