Python Database Connectivity
Python database connectivity refers to the tools and libraries that let a Python program connect to a relational database, run SQL queries, and pull the results back into Python for further analysis - bridging the two worlds covered so far in this course.
Why Connect Python to a Database
- Automate data extraction instead of manually exporting query results
- Combine the querying power of SQL with Python's analysis and visualization libraries
- Build repeatable pipelines that pull fresh data on a schedule
Common Python Database Libraries
- sqlite3 - built into Python, works with SQLite databases
- psycopg2 - connects to PostgreSQL databases
- mysql-connector-python / PyMySQL - connects to MySQL databases
- SQLAlchemy - a higher-level toolkit that works across many database types with a consistent interface
The General Workflow
# 1. Connect to the database
# 2. Create a cursor to execute queries
# 3. Run a query
# 4. Fetch the results
# 5. Close the connection
Each database type needs its own driver library - the exact package you install depends on which database (MySQL, PostgreSQL, SQLite, etc.) you're connecting to.