CodingNic

Databases and Persistence

Querying Data

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:

python
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

bash
python database.py

Output

text
(1, 'John')
(2, 'Alice')
(3, 'Bob')

Step 2: Get One User by ID

Now let’s fetch a specific user.

Update your code:

python
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

bash
python database.py

Output

text
(1, 'John')

What Changed?

WHERE Clause

sql
SELECT * FROM users WHERE id = ?
  • WHERE filters the data
  • Only returns matching rows

fetchone()

  • Returns one row
  • Instead of a list

Step 3: Try Different IDs

Change:

python
user_id = 2

Run again.

You should see:

text
(2, 'Alice')

Important Concept

You now know two types of queries:

  • fetchall() → multiple rows
  • fetchone() → 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 WHERE to filter data

In the next lesson, you’ll update and delete data.