🐍 Lesson 24: SQLite Basics
1. What is SQLite?
In short → SQLite is a lightweight database engine that comes built into Python. You don't need to set up a separate server — it stores your data as a single file.
In other words → SQLite is a lightweight, file-based database engine built into Python. It doesn't require a separate server and stores data in a single file.
2. Why Use SQLite?
- Easy setup (already included in Python)
- File-based (the DB is stored as a .db file)
- Great for small projects, testing, and prototyping
3. Summary
✅ SQLite = lightweight, file-based DB
✅ Python already includes the sqlite3 module
✅ CRUD operations → Create, Read, Update, Delete
✅ Use parameterized queries (?) for safety
python
# ===== 1. Connecting to SQLite =====
import sqlite3
conn = sqlite3.connect("mydatabase.db")
cursor = conn.cursor()
print("Database connected")
# ===== 2. Creating a Table =====
print(f"\n===== Create Table =====")
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER
)
""")
print("Table 'users' created")
# ===== 3. Inserting Data =====
print(f"\n===== Insert Data =====")
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Sai", 25))
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Aye", 30))
conn.commit()
print("Data inserted")
# ===== 4. Reading Data =====
print(f"\n===== Read Data =====")
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
print(f"ID: {row[0]}, Name: {row[1]}, Age: {row[2]}")
# ===== 5. Updating Data =====
print(f"\n===== Update Data =====")
cursor.execute("UPDATE users SET age = ? WHERE name = ?", (26, "Sai"))
conn.commit()
print("Data updated")
# ===== 6. Deleting Data =====
print(f"\n===== Delete Data =====")
cursor.execute("DELETE FROM users WHERE name = ?", ("Aye",))
conn.commit()
print("Data deleted")
# ===== 7. Closing Connection =====
conn.close()
print("\nConnection closed")You should see
Database connected ===== Create Table ===== Table 'users' created ===== Insert Data ===== Data inserted ===== Read Data ===== ID: 1, Name: Sai, Age: 25 ID: 2, Name: Aye, Age: 30 ===== Update Data ===== Data updated ===== Delete Data ===== Data deleted Connection closed