CRUD stands for Create, Read, Update, and Delete—the four foundational data manipulation operations powering nearly every software application and REST API. In this guide, we explore how to perform each operation efficiently using Python's sqlite3 module.
1. Setting Up Our Sample Schema
Let's work with an e-commerce products table:
1import sqlite3
2
3defget_connection():
4 conn = sqlite3.connect("store.db")
5 conn.row_factory = sqlite3.Row
6return conn
7
8with get_connection()as conn:
9 conn.execute("""
10 CREATE TABLE IF NOT EXISTS products (
11 id INTEGER PRIMARY KEY AUTOINCREMENT,
12 name TEXT NOT NULL,
13 category TEXT NOT NULL,
14 price REAL NOT NULL,
15 stock INTEGER DEFAULT 0
16 );
17 """)
2. CREATE: Single and Bulk Inserts
Single Insert (cursor.lastrowid)
When inserting a single record, cursor.lastrowid retrieves the auto-generated primary key:
Avoid looping over single execute() statements for thousands of records. Calling cursor.executemany() executes the batch within a single optimized transaction:
1inventory_batch =[
2("USB-C Fast Charger 65W","Electronics",1499.0,100),
Instead of permanently wiping records from disk, enterprise applications add an is_active or deleted_at column:
1-- Soft Delete: Flag record as inactive rather than deleting bytes
2UPDATE products SET is_active =0WHERE id =10;
3
4-- Query only active items:
5SELECT*FROM products WHERE is_active =1;
⚠️ Common Intermediate Mistakes & Gotchas
1. SQL Injection via String Interpolation
Never format user input into SQL queries using f-strings or %s. Always use parameterized queries with ? placeholders:
1# ❌ DANGEROUS SQL INJECTION VULNERABILITY
2cursor.execute(f"SELECT * FROM users WHERE name = '{user_input}'")
3
4# ✅ SECURE PARAMETERIZED QUERY
5cursor.execute("SELECT * FROM users WHERE name = ?",(user_input,))
2. UPDATE or DELETE Without a WHERE Clause
Executing an UPDATE or DELETE statement without a WHERE clause modifies or deletes EVERY row in the entire table!
💻 Try It Yourself: Complete CRUD Lifecycle Script
Scenario
Write an end-to-end Python script that inserts a record into an SQLite table, reads it back, updates its price, and finally deletes the record using parameterized queries.
Complete Solution
1import sqlite3
2
3with sqlite3.connect(":memory:")as conn:
4 cur = conn.cursor()
5 cur.execute("CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT, price REAL)")
6
7# 1. CREATE
8 cur.execute("INSERT INTO books (title, price) VALUES (?, ?)",("Python Mastery",599.0))
9 book_id = cur.lastrowid
10print(f"Created Book ID: {book_id}")
11
12# 2. READ
13 cur.execute("SELECT * FROM books WHERE id = ?",(book_id,))
14print("Read Record:", cur.fetchone())
15
16# 3. UPDATE
17 cur.execute("UPDATE books SET price = ? WHERE id = ?",(499.0, book_id))
18print("Updated price to ₹499.00.")
19
20# 4. DELETE
21 cur.execute("DELETE FROM books WHERE id = ?",(book_id,))
22print(f"Deleted Book ID: {book_id}. Remaining records: {cur.execute('SELECT COUNT(*) FROM books').fetchone()[0]}")
Expected Output
1Created Book ID: 1
2Read Record: (1, 'Python Mastery', 599.0)
3Updated price to ₹499.00.
4Deleted Book ID: 1. Remaining records: 0
Interactive Quiz• Knowledge Check
Practice Quiz
Question 1
Which method on a cursor should you use to insert a list of 500 records in a single batch?
Question 2
How can you retrieve the auto-generated primary key of the most recently inserted row?
Question 3
What cursor attribute indicates the number of rows affected by an UPDATE or DELETE statement?
Question 4
What critical mistake happens if an UPDATE statement is executed without a WHERE clause?
Question 5
What is the primary difference between a "Hard Delete" and a "Soft Delete"?
🚀 What's Next?
In the next lesson, we will continue your intermediate Python journey with Project: Student Records Database (11: Database Basics with SQLite).