smartyfy.mrindigi.com

Python Master Course V2 — 085. CRUD Operations

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · LESSON 085 OF 200 · MODULE 09 — DATABASES AND SQLITE

CRUD Operations

Study time: 70–100 minutes. Prerequisites: functions, exceptions, structured data and Lesson 84.

Course hub

Video

Video not yet available. This section is reserved for a verified lesson video URL or embedded player.

Learning outcomes

Create, read, update and delete records safely. Explain the concept, trace a sample program, test a boundary condition and implement a small real-world solution.

Detailed explanation

CRUD describes the lifecycle of stored records. Always scope UPDATE and DELETE statements carefully and confirm the affected rows.

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: CRUD Operations

CRUD is four distinct contracts

Create inserts a new record and returns its identity. Read retrieves a record or reports that it is absent. Update changes specified fields of an existing record. Delete removes a record; an archive operation instead marks it inactive so it can be restored. A task manager should define these outcomes before implementing its menu or web interface.

A primary-key WHERE clause scopes an update to a single intended row. Without WHERE, an UPDATE or DELETE affects all matching table rows, which may mean the entire table. Binding a parameter prevents SQL injection but does not compensate for a missing filter. Check rowcount after a mutation expected to affect one row; zero means the target did not match, not that an exception must have occurred.

Python example

import sqlite3
from contextlib import closing

with closing(sqlite3.connect(":memory:")) as db:
    db.execute("""CREATE TABLE tasks (
        id INTEGER PRIMARY KEY,
        title TEXT NOT NULL,
        done INTEGER NOT NULL DEFAULT 0 CHECK(done IN (0, 1)),
        archived INTEGER NOT NULL DEFAULT 0 CHECK(archived IN (0, 1))
    )""")
    with db:
        task_id = db.execute("INSERT INTO tasks(title) VALUES (?)", ("Read SQL",)).lastrowid
    print(db.execute("SELECT title, done FROM tasks WHERE id = ?", (task_id,)).fetchone())
    with db:
        changed = db.execute("UPDATE tasks SET done = ? WHERE id = ?", (1, task_id))
        if changed.rowcount != 1:
            raise LookupError("task not found")
        db.execute("UPDATE tasks SET archived = 1 WHERE id = ?", (task_id,))
    print(db.execute("SELECT title FROM tasks WHERE archived = 0").fetchall())
    with db:
        db.execute("UPDATE tasks SET archived = 0 WHERE id = ?", (task_id,))
    print(db.execute("SELECT title, done FROM tasks WHERE id = ?", (task_id,)).fetchone())
    print(db.execute("SELECT title FROM tasks WHERE id = ?", (999,)).fetchone())

Expected output

('Read SQL', 0)
[]
('Read SQL', 1)
None

The generated ID connects each later action to the created row. Completing and archiving occur in one transaction here, so an escaping failure would undo both. The active list is empty because the task is archived, not because its row vanished. Restoring archived to zero reveals the completed task again. A missing lookup returns None, which must be checked before unpacking or indexing.

Make deletion deliberate

For a disposable practice row, DELETE FROM tasks WHERE id=? removes it, and the cursor’s rowcount tells you whether a row existed. In an application, choose between archive and deletion based on recovery and audit requirements. Archive is a reversible state change, but it is not a backup: a later destructive database operation can still remove the row.

Validate a title before insertion, for example requiring a trimmed nonblank string with an explicit maximum length. The schema shown demonstrates lifecycle flags; it does not enforce that complete title policy. Keep user-facing validation separate from SQL, and avoid presenting every IntegrityError as “task not found,” because uniqueness and other constraints are different problems.

Test creation and immediate lookup, an unknown ID, completing an already-completed task, archive/restore, and a failed multi-step operation. When reporting counts, distinguish matched rows from meaningful business transitions: assigning the same value can still match a row. Define whether repeated completion is harmless success or a separate “already completed” result instead of inferring it solely from rowcount.

Runnable Python example

Requires Python 3.10+. Save as lesson85.py, run with python lesson85.py or python3 lesson85.py. Examples use only the standard library.

import sqlite3
from contextlib import closing
with closing(sqlite3.connect(':memory:')) as c:
    c.execute('CREATE TABLE tasks(id INTEGER PRIMARY KEY, done INTEGER)')
    c.execute('INSERT INTO tasks(done) VALUES (?)',(0,))
    c.execute('UPDATE tasks SET done=? WHERE id=?',(1,1))
    print(c.execute('SELECT done FROM tasks WHERE id=?',(1,)).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: Build a task manager with create, list, update and reversible archive actions.

  1. Specify the data schema and constraints in a small requirements table.
  2. Create a sample dataset with typical, boundary and invalid records.
  3. Implement separate functions for validation, transformation and reporting.
  4. Handle expected errors with informative messages.
  5. Write three automated tests and compare actual with expected results.
  6. 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.

Why store the lastrowid returned after insertion?

It is the new row’s identity for later reads and updates. Guessing that every new task is ID 1 breaks as soon as the table contains more data.

Does a missing UPDATE target always raise an exception?

No. A valid UPDATE can affect zero rows. Check rowcount and translate zero into the missing-target behavior your function promises.

How is archive different from DELETE?

Archive changes a status flag and preserves the row for restoration. DELETE removes the row. Both need a carefully scoped WHERE clause.

Why is the active-task list empty after archiving?

The SELECT filters archived = 0. The row still exists with archived = 1, so it is intentionally excluded rather than lost.

What should happen before indexing a lookup result?

Check whether fetchone returned None. If it did, raise or return the documented not-found result instead of triggering an unrelated indexing error.

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.

Course hub · Previous Lesson 84 in course hub · Continue with the next published lesson using the lesson navigation.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.