How to Fix 'ModuleNotFoundError: No Module Named psycopg2' in Python
Last Updated :
26 Apr, 2025
The psycopg2 package in Python interacts with PostgreSQL databases, providing an interface for executing SQL queries and managing database connections. If you encounter the 'ModuleNotFoundError: No Module Named psycopg2' error, it typically means that the package is not installed in your Python environment.
ModuleNotFoundErrorThis article discusses how to fix 'ModuleNotFoundError: No Module Named psycopg2'.
Why This Error Occurs
There are two main reasons:
1. Module Not Installed
In this scenario, we are trying to import the psycopg2 module in the code snippet where the data is to be fetched from the Endpoint. But, as the module psycopg2 is not installed on the system, the Python Code Error: No Module Named ‘psycopg2’ will occur.
Python
import psycopg2
conn = psycopg2.connect(
dbname="geeksforgeeks_db",
user="gfguser",
password="pass123",
host="localhost",
port="5432"
)
cur = conn.cursor()
cur.execute("SELECT * FROM articles WHERE source = 'GeeksforGeeks';")
rows = cur.fetchall()
for row in rows:
print(row)
cur.close()
conn.close()
Output:
ModuleNotFoundError: No module named 'psycopg2'
2. Incorrect Module Name
Another reason for the error might be a typo or incorrect naming when trying to import the psycopg2 module. Python is case-sensitive, so ensure that the module name is spelled correctly.
Python
import PSYCOPG2 # Wrong capitalization
Output:
ModuleNotFoundError: No module named 'PSYCOPG2'
How to Fix It
Below, are the approaches to solve “Modulenotfounderror: No Module Named ‘psycopg2′”.
Option 1: Install psycopg2 Module
We can resolve this error by installing the psycopg2 package externally using the PIP. Execute the below command in the prompt to install the package.
pip3 install psycopg2
Once we execute the command, it will take a couple of minutes to completely install the package according to the internet speed.
Option 2: Verify Module Name
Double-check the spelling and case sensitivity of the module name when importing it into your script.
Python
import psycopg2 # Correct
Also read: Python, PostgreSQL, psycopg2.