Last modified: Apr 07, 2025 By Alexander Williams
How to Install Psycopg2 in Python Step by Step
Psycopg2 is a popular PostgreSQL adapter for Python. It allows you to connect to PostgreSQL databases. This guide will show you how to install it.
Prerequisites
Before installing Psycopg2, ensure you have Python and PostgreSQL installed. You also need pip, Python's package installer.
Check Python version using python --version
. For pip, use pip --version
.
python --version
pip --version
Install Psycopg2 Using pip
The easiest way to install Psycopg2 is via pip. Open your terminal or command prompt and run the following command.
pip install psycopg2-binary
The psycopg2-binary package is a pre-compiled version. It's easier to install but may not be suitable for production.
Verify the Installation
After installation, verify it works. Open a Python shell and try importing Psycopg2.
import psycopg2
print("Psycopg2 installed successfully")
Psycopg2 installed successfully
Install Psycopg2 from Source
For production, install from source. First, install dependencies.
sudo apt-get install libpq-dev python3-dev
Then install Psycopg2 using pip.
pip install psycopg2
Common Installation Errors
If you encounter ModuleNotFoundError, check our guide on how to solve ModuleNotFoundError.
Another common error is missing dependencies. Ensure you have libpq-dev and python3-dev installed.
Connect to PostgreSQL
After installation, test the connection. Replace placeholders with your database details.
import psycopg2
conn = psycopg2.connect(
dbname="your_db",
user="your_user",
password="your_pass",
host="localhost"
)
print("Connected to PostgreSQL")
conn.close()
Connected to PostgreSQL
Conclusion
Installing Psycopg2 is simple with pip. Use psycopg2-binary for quick setup. For production, install from source.
Now you can connect Python to PostgreSQL. Happy coding!