53

これはかなり基本的な質問だと思いますが、理由がわかりません。

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")

Ubuntu12.04のPython2.7.3で最新のpsycopg2バージョンを使用しています

4

3 に答える 3

77

モジュールを使用しurlparseてURLを解析し、その結果を接続メソッドで使用します。このようにして、psycop2の問題を克服することが可能です。

from urlparse import urlparse # for python 3+ use: from urllib.parse import urlparse
result = urlparse("postgresql://postgres:postgres@localhost/postgres")
username = result.username
password = result.password
database = result.path[1:]
hostname = result.hostname
port = result.port
connection = psycopg2.connect(
    database = database,
    user = username,
    password = password,
    host = hostname,
    port = port
)
于 2013-03-26T12:05:05.603 に答える
27

に渡される接続文字列は、:psycopg2.connectによって解析されません。psycopg2逐語的にに渡されlibpqます。接続URIのサポートはPostgreSQL9.2で追加されました

于 2015-09-15T15:06:02.427 に答える
1

これを更新するために、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:
  ...

于 2022-02-16T09:13:03.023 に答える