连接到postgres中的URI

Daa*_*ker 32 python psycopg2

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

import psycopg2
psycopg2.connect("postgresql://postgres:postgres@localhost/postgres")
Run Code Online (Sandbox Code Playgroud)

给出以下错误:

psycopg2.OperationalError: missing "=" after
"postgresql://postgres:postgres@localhost/postgres" in connection info string
Run Code Online (Sandbox Code Playgroud)

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

psycopg2.connect("host=localhost user=postgres password=postgres dbname=postgres")
Run Code Online (Sandbox Code Playgroud)

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

小智 43

我会使用该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
)
Run Code Online (Sandbox Code Playgroud)

  • 我终于发现了问题所在.是否支持URI连接字符串不取决于您的`PostgresQL`版本(而不是您的`psycopg2`版本).我正在运行不支持它们的PostgresQL版本9.1. (16认同)
  • 我不认为这取决于 **PostgreSQL** 版本,而是 psycopg2 使用的 libpq 版本。 (4认同)
  • 我很欣赏这个想法,但我希望能找到一些更普遍的东西来接受任何`RFC 3986` URI postgres会接受的东西. (3认同)
  • @Daan的这个建议解决了我的问题,谢谢!如果可以选择升级到较新版本的postgres,请执行此操作.此外,请注意您必须删除(例如`pip uninstall psycopg2`),然后在升级postgres后重新安装(例如`pip install psycopg2`). (2认同)

kyn*_*nan 15

传递给的连接字符串psycopg2.connect不会被解析psycopg2:它被逐字传递给libpq.PostgreSQL 9.2中添加了对连接URI的支持.


mik*_*lam 7

为了更新这一点,Psycopg3 实际上包含了一种解析数据库连接 URI 的方法。

例子:

import psycopg # must be psycopg 3

pg_uri = "postgres://jeff:hunter2@example.com/db"
conn_dict =  psycopg.conninfo.conninfo_to_dict(pg_uri)

with psycopg.connect(**conn_dict) as conn:
  ...

Run Code Online (Sandbox Code Playgroud)