Databases and Persistence
15 min read
Updating and Deleting Data
Updating and Deleting Data
You can now create and read data.
Next, you will learn how to:
- Update existing data
- Delete data
This completes the core operations of a database.
What You Will Do
You will:
- Update a user’s name
- Delete a user
- Verify the changes
Step 1: Update a User
Update database.py:
import sqlite3
conn = sqlite3.connect("database.db")
cursor = conn.cursor()
user_id = 1
new_name = "John Updated"
cursor.execute(
"UPDATE users SET name = ? WHERE id = ?",
(new_name, user_id)
)
conn.commit()
conn.close()
print("User updated successfully")
Run It
python database.py
Step 2: Verify the Update
Use this code:
import sqlite3
conn = sqlite3.connect("database.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
users = cursor.fetchall()
for user in users:
print(user)
conn.close()
Expected Output
(1, 'John Updated')
(2, 'Alice')
(3, 'Bob')
Step 3: Delete a User
Now delete a user.
import sqlite3
conn = sqlite3.connect("database.db")
cursor = conn.cursor()
user_id = 2
cursor.execute(
"DELETE FROM users WHERE id = ?",
(user_id,)
)
conn.commit()
conn.close()
print("User deleted successfully")
Run It
python database.py
Step 4: Verify Deletion
Run the query again:
cursor.execute("SELECT * FROM users")
Expected:
(1, 'John Updated')
(3, 'Bob')
Important Concepts
UPDATE
UPDATE users SET name = ? WHERE id = ?
- Changes existing data
DELETE
DELETE FROM users WHERE id = ?
- Removes data permanently
⚠️ Important Warning
Always use WHERE when updating or deleting.
Without it:
- You may update ALL rows
- You may delete ALL data
Why This Matters
You can now:
- Modify existing data
- Remove unwanted data
- Fully manage your database
This completes CRUD:
- Create
- Read
- Update
- Delete
Common Mistakes
- ❌ Forgetting
WHERE - ❌ Forgetting
conn.commit() - ❌ Using wrong ID
Summary
- You updated a user
- You deleted a user
- You completed full database operations
In the next lesson, you’ll use SQLAlchemy to make this easier inside Flask.