Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't connect to remote postgreSQL using psycopg2

I am trying to connect to a remote postgreSQL database, using the following code:

import psycopg2


try:

    # this:
    conn = psycopg2.connect(database="A B C", user="user", password="pass", host="yyyy.xxxxx.com", port= 5432)
    # or this:
    conn = psycopg2.connect("dbname=A B C user=user password=pass host=yyyy.xxxxx.com port=5432")
    # or this:
    conn = psycopg2.connect("dbname='A B C' user='user' password='pass' host='yyyy.xxxxx.com' port=5432")

    print "connected"

except psycopg2.Error as e:
    print "I am unable to connect to the database"
    print e.pgcode
    print e.pgerror

So if I am sure I have the correct database name, which has spaces in it like "A B C" in my example, and the correct username/password/host/port, why can I not connect? Also, why does no error get passed onto the exception handler? I am using python 2.7.9. Here is the output, which is the same for any of the psycopg2.connect statements:

I am unable to connect to the database
None
None
like image 696
traggatmot Avatar asked Feb 18 '26 02:02

traggatmot


1 Answers

You should see more info in e exception and also use very useful traceback module:

import traceback

...

except psycopg2.Error as e:
    print "I am unable to connect to the database"
    print e
    print e.pgcode
    print e.pgerror
    print traceback.format_exc()
like image 59
Michał Niklas Avatar answered Feb 20 '26 16:02

Michał Niklas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!