连接到postgres中的URI

时间:2013-03-26 09:58:21

标签: python psycopg2

我猜这是一个非常基本的问题,但我无法弄清楚原因:

import psycopg2
psycopg2.connect("postgresql://postgres:postgres@localhost/postgres")

发出以下错误:

psycopg2.OperationalError: missing "=" after
"postgresql://postgres:postgres@localhost/postgres" in connection info string

有什么想法吗?根据{{​​3}}我认为它应该有效,但它只是这样:

psycopg2.connect("host=localhost user=postgres password=postgres dbname=postgres")

我在Ubuntu12.04上使用Python2.7.3上最新的psycopg2版本

2 个答案:

答案 0 :(得分:39)

我会使用urlparse模块来解析url,然后在连接方法中使用结果。这样就可以克服psycop2问题。

import urlparse # for python 3+ use: from urllib.parse import urlparse
result = urlparse.urlparse("postgresql://postgres:postgres@localhost/postgres")
username = result.username
password = result.password
database = result.path[1:]
hostname = result.hostname
connection = psycopg2.connect(
    database = database,
    user = username,
    password = password,
    host = hostname
)

答案 1 :(得分:12)

传递给psycopg2.connect的连接字符串未由psycopg2解析:它逐字传递给libpqSupport for connection URIs was added in PostgreSQL 9.2