Connect to an URI in postgres

匿名 (未验证) 提交于 2019-12-03 02:54:01

问题:

I'm guessing this is a pretty basic question, but I can't figure out why:

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

Is giving the following error:

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

Any idea? According to the docs about connection strings I believe it should work, however it only does like this:

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

I'm using the latest psycopg2 version on Python2.7.3 on Ubuntu12.04

回答1:

The connection string passed to psycopg2.connect is not parsed by psycopg2: it is passed verbatim to libpq. Support for connection URIs was added in PostgreSQL 9.2.



回答2:

I would use the urlparse module to parse the url and then use the result in the connection method. This way it's possible to overcome the psycop2 problem.

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 ) 


回答3:

Try postgres as the scheme rather than postgresql



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!