Database Integration ๐¶
Mentor's Note: Lists and Files are great for small data. But if you have 1 million users, you need a Database. Python makes connecting to databases feel as easy as reading a dictionary! ๐ก
๐ The Scenario: The Digital Librarian ๐¶
Imagine you own a huge library with 1 million books.
- The Problem: You can't just put all books in one big pile (The List). You also can't put every book in its own drawer (The File). ๐ฆ
- The Logic: You hire a Librarian (The Database). You just hand them a note: "Find me every book by Vishnu."
- The Result: The librarian runs to the exact shelf and brings the books back instantly. Python is the Pen you use to write that note! โ
๐ Database Types in Python¶
1. SQLite (Built-in) ๐๏ธ¶
The easiest way to start. It requires NO installation. The database is just a file on your computer.
2. MySQL (The Industry Standard) ๐ข¶
Used for web servers and large apps. Requires a server and the mysql-connector-python library.
3. MongoDB (The NoSQL Choice) ๐¶
Stores data like JSON (Dictionaries). Very fast for "unstructured" data like social media posts.
๐จ Visual Logic: The CRUD Cycle¶
graph TD
A[Python Script ๐] -- CREATE --> B[Database ๐๏ธ]
A -- READ --> B
A -- UPDATE --> B
A -- DELETE --> B
B --> C[Permanent Storage โ
]
๐ป Implementation: The CRUD Lab¶
import sqlite3
# ๐ Action: Creating a simple student record
conn = sqlite3.connect("college.db")
cursor = conn.cursor()
# ๐๏ธ 1. Create table
cursor.execute("CREATE TABLE IF NOT EXISTS students (id INT, name TEXT)")
# ๐ฅ 2. Insert data
cursor.execute("INSERT INTO students VALUES (101, 'Vishnu')")
# ๐ 3. Save and Close
conn.commit()
conn.close()
print("Database Updated! โ
")
# Installation: pip install pymongo
from pymongo import MongoClient
# ๐ Action: Storing a dictionary as a 'Document'
client = MongoClient("mongodb://localhost:27017/")
db = client["school"]
collection = db["users"]
# ๐ MongoDB loves Python Dictionaries!
student = {"name": "Ankit", "grade": "A+"}
collection.insert_one(student)
๐ Sample Dry Run (Read)¶
Task: Fetch name from ID 101
| Step | Action | Logic | Result |
|---|---|---|---|
| 1 | cursor.execute |
Send SQL query to Librarian ๐ | Query queued. |
| 2 | cursor.fetchone |
Librarian brings 1 book ๐ | Row (101, 'Vishnu') |
| 3 | row[1] |
Open the 'Name' column | "Vishnu" โ
|
๐ Technical Analysis¶
- Transactions: Always use
.commit()after changes. If your program crashes halfway, the database will "Rollback" to keep your data safe. ๐ก๏ธ - Injection Attacks: NEVER use f-strings for SQL queries (e.g.,
WHERE name = '{user_input}'). This allows hackers to delete your table. Always use Parameterized Queries (?or%s). โ
๐ฏ Practice Lab ๐งช¶
Task: The Grade Updater
Task: Using SQLite, write a program that updates the grade of a student to 'A' based on their id.
Hint: UPDATE students SET grade = ? WHERE id = ?. ๐ก
๐ก Interview Tip ๐¶
"Interviewers love asking about ORMs (Object Relational Mappers). Mention that in professional projects, we use SQLAlchemy or Django ORM to avoid writing raw SQL!"
๐ก Pro Tip: "A database is a repository of truth. Protect it with good constraints and clean code!" - Anonymous
โ Back: Specialized Libraries | Next: GUI with Tkinter โ