首页 > 解决方案 > 无法在 python 中连接到远程 Postgresql 数据库

问题描述

我想用 Python 连接到远程 Postgresql(安装在树莓派上)数据库。我已按照以下链接中的示例进行操作:

https://opensource.com/article/17/10/set-postgres-database-your-raspberry-pi

使用以下代码:

conn = psycopg2.connect('host=192.xxx.x.x user=pi password = raspberry dbname = test')

不知道出了什么问题。任何人的解决方案。

不幸的是,我收到以下错误:

psycopg2.OperationalError:致命:用户“pi”的密码验证失败 致命:用户“pi”的密码验证失败

标签: pythonpostgresqlraspberry-piremote-access

解决方案


我强烈建议提供凭据作为关键字参数以提高可读性:

psycopg2.connect(
    user="...",
    password="...",
    dbname="...",
    host="...",
)

此外,正如评论中提到的@peterh,您提供的凭据可能被错误地解析(但在这种情况下不是)。您可以使用psycopg2自己的解析器来确认输出:

psycopg2._psycopg.parse_dsn('host=192.xxx.x.x user=pi password = raspberry dbname = test')

返回:

{'user': 'pi',
 'password': 'raspberry',
 'dbname': 'test',
 'host': '192.xxx.x.x'}

考虑到所有因素,您的错误表明用户/密码组合不正确。


推荐阅读