Database Integration πΒΆ
Prerequisites: Python Dictionaries, SQL Basics (Conceptual)
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 β