Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 720
adan11 Avatar asked Feb 22 '26 07:02

adan11


2 Answers

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

import psycopg2
from urllib.parse import urlparse

conStr = "postgres://username:password@localhost:5432/data_quality"
p = urlparse(conStr)

pg_connection_dict = {
    'dbname': p.path[1:],
    'user': p.username,
    'password': p.password,
    'port': p.port,
    'host': p.hostname
}

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>
like image 178
Maurice Meyer Avatar answered Feb 23 '26 21:02

Maurice Meyer


Documentation for pyscopg2 connect is here. Following their syntax you connect like this:

connection = psycopg2.connect(host='localhost', user='<username>',
                              password='<password>', 
                              dbname='data_quality', port=5432)

If you are using Windows, it can be stupid about resolving localhost if you don't have a network connection. You can get around this by instead using '127.0.0.1' for host

like image 36
bfris Avatar answered Feb 23 '26 21:02

bfris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!