我猜这是一个非常基本的问题,但我无法弄清楚原因:
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)
为了更新这一点,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)