无法使用psycopg2连接到远程的postgreSQL数据库。

3

我正在尝试使用以下代码连接到远程的postgreSQL数据库:

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

如果我确定我有正确的数据库名称,例如我的示例中带有空格的“A B C”,以及正确的用户名/密码/主机/端口,为什么我无法连接?另外,为什么没有错误传递到异常处理程序?我正在使用Python 2.7.9。以下是输出,对于任何psycopg2.connect语句都是相同的:

I am unable to connect to the database
None
None

据我所知,在PostgresQL模式名称中不允许使用空格。这也是我从http://www.postgresql.org/docs/9.2/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS阅读到的内容。 - Klaus D.
并非每个 psycopg2 异常都设置了 pgcodepgerror。您应该打印 e 以查看实际的异常消息。 - Lukas Graf
谢谢,你们俩的帮助很大。我的同事坚持认为数据库名称就是所呈现的那样,但由于我现在能看到的错误信息表明它并不正确。 - traggatmot
通过pgAdmin检查了名称,即使没有空格,但是psycopg2告诉我它不存在。 - traggatmot
1个回答

4

您应该在e异常中看到更多信息,并使用非常有用的traceback模块:

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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接