I am trying to connect to postgresql using the following code
import psycopg2
hostname = 'localhost'
database = 'demo'
username = 'postgres'
pwd = 'johndoe'
port_d= 5432
conn = psycopg2.connect(
host=hostname,
dbname=database,
user = username,
password=pwd,
port = port_d)
conn.close()
I have installed psycopg2 using pip install psycopg2
.
Somehow when I try establishing a connection I get this error.
Im not sure what I am doing wrong
Traceback (most recent call last):
File "/Users/abiodunadeoye/KINGS-PLATFORM/Postgres/ETL/connect.py", line 1, in <module>
import psycopg2
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/psycopg2/__init__.py", line 51, in <module>
from psycopg2._psycopg import ( # noqa
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/psycopg2/_psycopg.cpython-37m-darwin.so, 0x0002): Library not loaded: @rpath/libpq.5.dylib
Referenced from: <D5013EE3-2219-32DC-A518-A4DA08CF3918> /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/psycopg2/_psycopg.cpython-37m-darwin.so
Reason: tried: '/usr/local/lib/libpq.5.dylib' (no such file), '/usr/lib/libpq.5.dylib' (no such file, not in dyld cache)
3
Answers
If we’re just talking for local use, you want to use the standalone psycopg2-binary package:
Otherwise it will try to dynamically link libpq, which you apparently don’t have on your system. See the psycopg2 documentation for a discussion of the difference. If you want to use the non-standalone version you will need to install
libpq
andlibssl
with homebrew and symlink them to the appropriate locations that psycopg2 expects to find them.Faced a similar issue on mac.
This fixed it for me:
sudo ln -s /opt/homebrew/opt/postgresql@14/lib/postgresql@14/libpq.5.dylib /usr/local/lib/libpq.5.dylib
Basically, this creates a symbolic link for ‘libpq.5.dylib’ in ‘/usr/local/lib/’ directory. This link points to the original ‘libpq.5.dylib’ library file located in my PostgreSQL 14 installation through Homebrew.
A quick fix for this would be to install the
psycopg2-binary
standalone package which contains the necessary PostgreSQL client libraries. This would help with the library loading issues you are currently encountering.