Psycopg2 - 使用连接字符串连接到PostgreSQL数据库

7

我目前有一个格式如下的连接字符串:

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

使用psycopg2连接到我的数据库最好的方法是什么?

例如:

connection = psycopg2.connect(connection_string)

谢谢!

2个回答

9
你可以利用urlparse,创建一个与psycopg的连接参数相匹配的字典:
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)

输出:

{'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>

3

关于pyscopg2的connect文档可以在这里找到。按照他们的语法,你可以像这样连接:

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

如果您使用的是Windows操作系统,在没有网络连接的情况下,它可能无法正确解析“localhost”。您可以通过使用“127.0.0.1”替代“host”来解决这个问题。请注意保留HTML标签。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接