关于python:连接到postgres中的URI

Connect to an URI in postgres

我猜这是一个非常基本的问题,但我不知道为什么:

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

正在给出以下错误:

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

任何想法? 根据有关连接字符串的文档,我认为它应该可以工作,但是它只是这样做:

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

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


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

1
2
3
4
5
6
7
8
9
10
11
12
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
)


传递给psycopg2.connect的连接字符串不被psycopg2解析:将其原样传递给libpq。 在PostgreSQL 9.2中添加了对连接URI的支持。