我目前有一个格式如下的连接字符串:
"localhost://username:password@data_quality:5432"
使用psycopg2连接到我的数据库最好的方法是什么?
例如:
connection = psycopg2.connect(connection_string)
谢谢!
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>
关于pyscopg2的connect
文档可以在这里找到。按照他们的语法,你可以像这样连接:
connection = psycopg2.connect(host='localhost', user='<username>',
password='<password>',
dbname='data_quality', port=5432)