3

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
asked Mar 9, 2015 at 19:33
4
  • AFAIK spaces are not allowed in PostgresQL schema names. Which is also what I read from postgresql.org/docs/9.2/static/… Commented Mar 9, 2015 at 19:46
  • Not every psycopg2 exception has pgcode or pgerror set. You should print e as well to see the actual exception message. Commented Mar 9, 2015 at 19:51
  • Thanks, big help from both of you. My colleague insists that database name is as presented, which maybe incorrect since the error I can now see says it is not. Commented Mar 9, 2015 at 19:57
  • Checked the name using pgAdmin and it is definitely correct without the spaces even though I am being told by psycopg2 that it doesn't exist. Commented Mar 9, 2015 at 20:36

1 Answer 1

4

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()
answered Mar 10, 2015 at 13:27
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.