You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Psycopg 3.x是否可禁用扩展查询协议?连接Pgbouncer遇报错

解决Psycopg3连接Pgbouncer执行SHOW STATS时的ProtocolViolation错误

问题描述

使用psycopg==3.1.19连接pgbouncer,尝试执行SHOW STATS(该指令由pgbouncer直接响应,不会发送至PostgreSQL)时,收到错误:

ProtocolViolation: extended query protocol not supported by admin console

用户原代码:

import psycopg
from psycopg.rows import dict_row

conn = psycopg.connect("host=127.0.0.1 port=6432 user=myuser password=mypass dbname=pgbouncer ", row_factory=dict_row, autocommit=False)
conn.prepare_threshold = None
conn.prepared_max = 0

cur = conn.cursor()
cur.execute("SHOW STATS") # ProtocolViolation: extended query protocol not supported by admin console

解决方案

不需要降级到Psycopg2,Psycopg3提供了适配Pgbouncer admin控制台的方法——使用连接对象的simple_query()方法,该方法默认采用简单查询协议,不会触发扩展协议相关的限制。

修改后的代码示例:

import psycopg
from psycopg.rows import dict_row

# 执行Pgbouncer admin命令建议开启autocommit
conn = psycopg.connect(
    "host=127.0.0.1 port=6432 user=myuser password=mypass dbname=pgbouncer ",
    row_factory=dict_row,
    autocommit=True
)

# 使用simple_query执行SHOW STATS,自动使用简单查询协议
results = conn.simple_query("SHOW STATS")
# 将结果转换为字典列表(因设置了row_factory=dict_row)
stats_list = list(results)

# 查看结果
for stat in stats_list:
    print(stat)

关键说明:

  • simple_query()方法直接与Pgbouncer的admin控制台兼容,绕过了Psycopg3默认的扩展查询协议;
  • 执行Pgbouncer的admin命令必须开启autocommit=True,因为这类命令不支持事务操作,原代码中autocommit=False会导致额外问题;
  • 设置row_factory=dict_row可以让返回结果保持字典格式,便于后续处理。

内容的提问来源于stack exchange,提问作者RubenLaguna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 08:24:59