Postgresql – Can’t connect to PostgreSQL instance using Python

connectivitypostgresqlpython

I have installed vagrant and virtual box on my laptop to finish a class I am working on. I have created a database called tournament. I can connect to it directly, create tables, insert data, etc.

However, I am trying to write a python script to connect to it and having great difficulty.

Here is my greatly simplified code:

import psycopg2

psycopg2.connect('dbname=tournament')

Here is what I am getting:

enter image description here

Any help would be greatly appreciated. I am really frustrated.

Best Answer

Since you did not specify the host argument of che connect call, you are connecting via a unix named pipe instead of TCP/IP, so the error message might be slightly incorrect. BTW, the database should have opened a pipe named /var/run/postgresql/.s.PGSQL.5432. Can you check if it exists using command ls -la /var/run/postgresql/.s*? You might find there a pipe with a different number, or you might find and empty directory. In the first case, just add port=number (using the right number) to the connect call; in the latter case, find the correct directory for your postgresql and add host=path (using the right path) to the connect call.

In order to find the correct path, connect via psql and give command \conninfo. In will display the correct path, as in:

postgres=# \conninfo
You are connected to database "postgres" as user "postgres" via socket in "/var/run/postgresql" at port "5432".

P.S. It might also be a problem of the syntax you used. It should be psycopg2.connect(dbname="tournament")