ModuleNotFoundError: No module named 'psycopg2'
Fixes ModuleNotFoundError: No module named 'psycopg2' Use when `create_engine('postgresql://...')` raises No module named 'psycopg2' Not for: `NoSuchModuleError: Can't load plugin` for a different dialect (that is a URL/dialect mismatch)
How to fix ModuleNotFoundError: No module named 'psycopg2'
SQLAlchemy does not ship a Postgres driver; a bare postgresql:// URL defaults to psycopg2. Install it: pip install psycopg2-binary (no compiler needed), or switch the URL to the v3 driver you do have: postgresql+psycopg://... with pip install "psycopg[binary]". The driver name in the URL must match the installed package.
The exact error
ModuleNotFoundError: No module named 'psycopg2'Fix it
- Check which driver you have:
python -m pip show psycopg2-binary psycopg.
Expected: you see which (if any) is installed
- Easiest:
python -m pip install psycopg2-binaryand keeppostgresql://.
Expected: create_engine connects
- Or go v3:
python -m pip install "psycopg[binary]"and change the URL topostgresql+psycopg://host/db.
Expected: connects via psycopg3
When this applies
create_engine('postgresql://...') raises No module named 'psycopg2'
When this does NOT apply
NoSuchModuleError: Can't load plugin for a different dialect (that is a URL/dialect mismatch)
Versions
SQLAlchemy with postgresql:// URLs
Why it happens
DBAPI drivers are separate packages by design; SQLAlchemy only knows the dialect name.
Edge cases
psycopg2 from source needs pg_config/libpq headers to build; psycopg2-binary avoids that. Keep the password in env vars, not code.
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.