连接到一个URI在postgres的(Connect to an URI in postgres)

2019-08-18 01:09发布

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

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

是给下面的错误:

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

任何的想法? 据有关连接字符串的文档 ,我相信它应该工作,但它只做这样的:

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

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

Answer 1:

传递给连接字符串psycopg2.connect不被解析psycopg2 :它是通过逐字到libpq 。 在PostgreSQL的9.2增加了对URI的连接支持 。



Answer 2:

我会用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
)


文章来源: Connect to an URI in postgres