Databases and Persistence
15 min read
Querying Data
Querying Data
You have stored data in your database.
Now you need to retrieve it.
This is called querying.
What You Will Do
You will:
- Read all users
- Read a single user by ID
- Display results
Step 1: Get All Users
Update database.py:
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()
Run It
python database.py
Output
(1, 'John')
(2, 'Alice')
(3, 'Bob')
Step 2: Get One User by ID
Now let’s fetch a specific user.
Update your code:
import sqlite3
conn = sqlite3.connect("database.db")
cursor = conn.cursor()
user_id = 1
cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
user = cursor.fetchone()
print(user)
conn.close()
Run It
python database.py
Output
(1, 'John')
What Changed?
WHERE Clause
SELECT * FROM users WHERE id = ?
WHEREfilters the data- Only returns matching rows
fetchone()
- Returns one row
- Instead of a list
Step 3: Try Different IDs
Change:
user_id = 2
Run again.
You should see:
(2, 'Alice')
Important Concept
You now know two types of queries:
fetchall()→ multiple rowsfetchone()→ single row
Why This Matters
This is how real apps work:
- View one user profile
- Load specific data
- Handle dynamic requests
Common Mistakes
- ❌ Forgetting
(user_id,)(must be a tuple) - ❌ Using
fetchall()when expecting one item - ❌ Wrong column name
Summary
- You retrieved all users
- You retrieved a single user
- You used
WHEREto filter data
In the next lesson, you’ll update and delete data.