python-3.x - 从 python psycopg2 客户端连接到 Azure PostgreSQL 服务器

标签 python-3.x postgresql azure psycopg2

我在从 python 连接到 Azure postgres 数据库时遇到问题。我正在遵循此处的指南 - https://learn.microsoft.com/cs-cz/azure/postgresql/connect-python 我有基本相同的代码来设置连接。 但是 psycopg2 和 SQLalchemy 给我抛出了同样的错误:

OperationalError: server closed the connection unexpectedly
  This probably means the server terminated abnormally
  before or while processing the request.

我可以通过其他客户端工具(例如 dbeaver)连接到该实例,但从 python 中它不起作用。

当我调查 Postgres 日志时,我可以看到服务器实际上授权了连接,但下一行显示

 could not receive data from client: An existing connection was forcibly closed by the remote host.

Python 是 3.7 psycopg的版本是2.8.5 Azure Postgres 区域位于西欧

有人对我应该如何使其发挥作用有任何建议吗?

谢谢!

编辑: 问题自行解决了。几天后我尝试了相同的设置,它开始工作。 Azure 西欧可能出了问题。

最佳答案

我也遇到这个问题了。我想我在某处读到过(我忘了在哪里),Azure 对于用户名 (user@serverName) 必须使用 @ 存在问题。

我创建了变量和一个 f 字符串,然后它工作正常。

import sqlalchemy    

username = 'user@server_name'
password = 'PassWord!'
host = 'server_name.postgres.database.azure.com'
database = 'your_database'

conn_str = f'postgresql+psycopg2://{username}:{password}@{host}/{database}'

之后:

engine = sqlalchemy.create_engine(conn_str, pool_pre_ping=True)
conn = engine.connect()

使用简单的 SQL 语句进行测试。

sql = 'SELECT * FROM public.some_table;'
results = conn.engine.execute(sql)

这是英国南部的转机。在此之前,它确实提示用户名的格式必须使用@,尽管用户名是正确的,从命令行使用 PSQL 和另一个 SQL 客户端进行测试。

关于python-3.x - 从 python psycopg2 客户端连接到 Azure PostgreSQL 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63059209/

相关文章:

PostgreSQL:带有 ANY($1) 的 PREPARED 语句

Spring Boot - 不同数据库的相同存储库和相同实体

c# - Azure 事件目录 |基于角色的授权

azure - MS Bot 初始启动速度更快

Python 网络爬行抛出连接错误

Python:创建幂等初始化器

excel - 将逗号分隔的单元格内容转换为同一列中的多个单元格

sql - 多对多对多 SQL 模式

azure - 根据 Azure ML Studio 中的条件替换列中的值

python-3.x - ipython3 笔记本垂直边距/标记线 80 个字符