| type | title | version | tags | |||
|---|---|---|---|---|---|---|
task |
Set Up PostgreSQL Database Connection |
1.0.0 |
|
This task walks you through configuring a connection to a PostgreSQL database from a Python application using the psycopg2 library.
- Python 3.8+ installed locally
- PostgreSQL server running (local or remote)
- Database name, host, port, username, and password available
pippackage manager
-
Install the PostgreSQL driver library
pip install psycopg2-binary
- Note:
psycopg2-binaryincludes pre-compiled libraries; usepsycopg2if you prefer to compile from source.
- Note:
-
Create a connection configuration file (optional but recommended) Create
db_config.py:DB_CONFIG = { "host": "localhost", "port": 5432, "database": "myapp_db", "user": "postgres", "password": "your_password" }
- Note: Never commit passwords to version control. Use environment variables in production.
-
Write a connection test script Create
test_connection.py:import psycopg2 from db_config import DB_CONFIG conn = psycopg2.connect(**DB_CONFIG) cursor = conn.cursor() cursor.execute("SELECT version();") db_version = cursor.fetchone() print(f"Connected to: {db_version}") cursor.close() conn.close()
-
Run the test script
python test_connection.py
- Note: You should see PostgreSQL version info printed to the console if successful.
Successful output looks like:
Connected to: ('PostgreSQL 12.8 on x86_64-pc-linux-gnu...')
If you see a psycopg2.OperationalError, check the host, port, username, and password in your config.
- Concept: PostgreSQL Connection Concepts — Understand connection pooling and security
- Reference: PostgreSQL Connection Parameters — All configuration options
- Troubleshooting: PostgreSQL Connection Errors — Debug connection issues
Why this structure works:
- Overview: Answers "what will I do?" in 1–2 sentences.
- Prerequisites: Reduces cognitive load. Reader knows upfront what they need.
- Steps: One action per step. Each step is independent and clear.
- Code blocks are included (realistic).
notefields explain context (why, what to expect), not the step itself.
- Verification: Concrete success criteria. "I'll see this output if it works."
- Related Documents: Links readers to deeper concepts (Concept), reference data (Reference), and error recovery (Troubleshooting).
What we avoid:
- No conceptual deep-dive (e.g., "Here's how psycopg2 works" — that goes in Concept)
- No troubleshooting procedures (e.g., "If you get a 'connection refused' error..." — that goes in Troubleshooting)
- No assumption of failure paths (readers with working setups don't need error recovery in the happy path)
This keeps the doc focused and scannable.