Search code examples
pythonpsycopg2

Psycopg2 - Connect to postgreSQL database using a connection string


I currently have a connection string in the format of:

"localhost://username:password@data_quality:5432"

What is the best method of using this to connect to my database using psycopg2? e.g.:

connection = psycopg2.connect(connection_string)

Solution

  • You could make use of urlparse, creating a dictionary that matches psycopg's connection arguments:

    import psycopg2
    from urllib.parse import urlparse
    
    conStr = "localhost://username:password@data_quality:5432"
    p = urlparse(conStr)
    
    pg_connection_dict = {
        'dbname': p.hostname,
        'user': p.username,
        'password': p.password,
        'port': p.port,
        'host': p.scheme
    }
    
    print(pg_connection_dict)
    con = psycopg2.connect(**pg_connection_dict)
    print(con)
    

    Out:

    {'dbname': 'data_quality', 'user': 'username', 'password': 'password', 'port': 5432, 'host': 'localhost'}
    <connection object at 0x105f58190; dsn: 'user=xxx password=xxx dbname=xxx host=xxx port=xxx', closed: 0>