57

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

Darek
  • 2,861
  • 4
  • 29
  • 52
Daan Bakker
  • 6,122
  • 3
  • 24
  • 23

4 Answers4

83

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.

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
)
luckydonald
  • 5,976
  • 4
  • 38
  • 58
joamag
  • 1,382
  • 1
  • 9
  • 15
  • 4
    I appreciate the idea, but I was hoping to find something more general that will accept any `RFC 3986` URI postgres would accept. – Daan Bakker Mar 26 '13 at 23:06
  • 1
    I guess this is some kind of psycop2 limitation you'll have to live with – joamag Mar 27 '13 at 01:33
  • 22
    I finally found out what the problem was. Whether URI connection strings are supported are not depends on your `PostgresQL` version (and NOT on your `psycopg2` version). I am running PostgresQL version 9.1 which does not support them. – Daan Bakker Apr 18 '13 at 13:57
  • 2
    This suggestion by @Daan solved my problem, thanks! If upgrading to a newer version of postgres is an option, do it. Also, note that you will have to remove (e.g. `pip uninstall psycopg2`) and then reinstall (e.g. `pip install psycopg2`) after upgrading postgres itself. – Markus Amalthea Magnuson Feb 26 '14 at 17:19
  • 4
    I don't think it depends on **PostgreSQL** version, but the libpq version that psycopg2 is using. – Antti Haapala -- Слава Україні Dec 19 '18 at 10:35
  • 1
    The urlparse module is renamed to urllib.parse in Python 3. – user3361149 May 08 '20 at 08:53
  • This is a bad answer. Any password containing `#` would be registered as having an URL fragment, and hence it'd put everything after `#` as a fragment. `postgresql://username:VeRyCoMpl#xPasSwOrD@super-postgres.com:5432/dbname` would be `ParseResult(scheme='postgresql', netloc='username:VeRyCoMpl', path='', params='', query='', fragment='xPasSwOrD@super-postgres.com:5432/dbname')` – Samuel Prevost Dec 14 '22 at 09:36
29

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.

kynan
  • 13,235
  • 6
  • 79
  • 81
7

To update on this, Psycopg3 does actually include a way to parse a database connection URI.

Example:

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:
  ...

mikkelam
  • 517
  • 1
  • 7
  • 15
2

Another option is using SQLAlchemy for this. It's not just ORM, it consists of two distinct components Core and ORM, and it can be used completely without using ORM layer.

SQLAlchemy provides such functionality out of the box by create_engine function. Moreover, via URI you can specify DBAPI driver or many various postgresql settings.

Some examples:

# default
engine = create_engine("postgresql://user:pass@localhost/mydatabase")
# psycopg2
engine = create_engine("postgresql+psycopg2://user:pass@localhost/mydatabase")
# pg8000
engine = create_engine("postgresql+pg8000://user:pass@localhost/mydatabase")
# psycopg3 (available only in SQLAlchemy 2.0, which is currently in beta)
engine = create_engine("postgresql+psycopg://user:pass@localhost/test")

And here is a fully working example:

import sqlalchemy as sa

# set connection URI here ↓
engine = sa.create_engine("postgresql://user:password@db_host/db_name")
ddl_script = sa.DDL("""
    CREATE TABLE IF NOT EXISTS demo_table (
        id serial PRIMARY KEY,
        data TEXT NOT NULL
    );
""")

with engine.begin() as conn:
    # do DDL and insert data in a transaction
    conn.execute(ddl_script)
    conn.exec_driver_sql("INSERT INTO demo_table (data) VALUES (%s)",
                         [("test1",), ("test2",)])

    conn.execute(sa.text("INSERT INTO demo_table (data) VALUES (:data)"),
                 [{"data": "test3"}, {"data": "test4"}])

with engine.connect() as conn:
    cur = conn.exec_driver_sql("SELECT * FROM demo_table LIMIT 2")
    for name in cur.fetchall():
        print(name)

# you also can obtain raw DBAPI connection
rconn = engine.raw_connection()

SQLAlchemy provides many other benefits:

  • You can easily switch DBAPI implementations just by changing URI (psycopg2, psycopg2cffi, etc), or maybe even databases.
  • It implements connection pooling out of the box (both psycopg2 and psycopg3 has connection pooling, but API is different)
  • asyncio support via create_async_engine (psycopg3 also supports asyncio).
Slava Bacherikov
  • 1,983
  • 13
  • 15