【问题标题】:Can't connect to remote postgreSQL using psycopg2无法使用 psycopg2 连接到远程 postgreSQL
【发布时间】:2015-03-09 19:33:50
【问题描述】:

我正在尝试使用以下代码连接到远程 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 模式名称中不允许使用 AFAIK 空格。这也是我从postgresql.org/docs/9.2/static/… 读到的
  • 并非每个psycopg2 异常都设置了pgcodepgerror。您还应该打印 e 以查看实际的异常消息。
  • 谢谢你们两位的大力帮助。我的同事坚持认为数据库名称与提供的一样,这可能是不正确的,因为我现在看到的错误表明它不是。
  • 使用 pgAdmin 检查了名称,即使 psycopg2 告诉我它不存在,但没有空格肯定是正确的。

标签: python postgresql psycopg2


【解决方案1】:

您应该在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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 2021-11-09
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    相关资源
    最近更新 更多