Lesson 9.3: Working with Databases (SQLite/MySQL)
Introduction:
Working with databases allows Python developers to store, retrieve, and manage data efficiently. This lesson covers connecting to databases, performing CRUD (Create, Read, Update, Delete) operations, and using SQLite (lightweight, file-based) or MySQL (server-based) databases.
1. SQLite – Lightweight Database:
-
No server required; stores data in a single file
-
Use Python’s built-in
sqlite3module
Example – Creating a Database and Table:
Example – Inserting Data:
Example – Querying Data:
2. MySQL – Server-Based Database:
-
Use mysql-connector-python to connect Python with MySQL
Installation:
Example – Connecting to MySQL:
3. Practical Tips:
-
Always close the connection after operations:
conn.close() -
Use parameterized queries to prevent SQL injection
-
For large projects, consider using ORMs like SQLAlchemy for easier database management
Learning Outcome of This Lesson:
-
Understand the difference between SQLite and MySQL
-
Connect Python programs to databases
-
Perform CRUD operations efficiently
-
Apply database handling in real-world Python applications
