【发布时间】: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异常都设置了pgcode或pgerror。您还应该打印e以查看实际的异常消息。 -
谢谢你们两位的大力帮助。我的同事坚持认为数据库名称与提供的一样,这可能是不正确的,因为我现在看到的错误表明它不是。
-
使用 pgAdmin 检查了名称,即使 psycopg2 告诉我它不存在,但没有空格肯定是正确的。
标签: python postgresql psycopg2