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

从psycopg2迁移至psycopg3:RealDictCursor替代方案咨询

Psycopg3 替代 RealDictCursor 的解决方案

方法1:直接使用 dict 作为行工厂

Psycopg3 原生支持将查询结果转为字典,无需额外导入特殊类。只需给游标设置 row_factory = dict 即可:

import psycopg
import json

# 建立连接
with psycopg.connect("your_connection_string") as conn:
    # 创建游标并设置行工厂为dict
    with conn.cursor(row_factory=dict) as cursor:
        cursor.execute("SELECT id, name FROM your_table")
        # 获取字典格式的结果列表
        results = cursor.fetchall()
        
        # 转为JSON文件
        with open("output.json", "w") as f:
            json.dump(results, f, indent=2)

方法2:使用官方提供的 dict_row 行工厂

Psycopg3 在 psycopg.rows 模块中提供了专门的 dict_row 行工厂,功能和效果与方法1一致,属于官方推荐的规范用法:

import psycopg
from psycopg.rows import dict_row
import json

with psycopg.connect("your_connection_string") as conn:
    # 也可以在连接时全局设置行工厂,后续所有游标默认使用
    # conn.row_factory = dict_row
    with conn.cursor(row_factory=dict_row) as cursor:
        cursor.execute("SELECT id, name FROM your_table")
        results = cursor.fetchall()
        
        with open("output.json", "w") as f:
            json.dump(results, f, indent=2)

补充说明

  • 两种方法都能直接得到键为列名、值为对应字段内容的字典列表,完全兼容你原来转JSON的逻辑,不需要手动遍历数据。
  • 如果需要全局生效,可以在建立连接时设置 conn.row_factory = dict 或者 dict_row,这样所有从该连接创建的游标都会自动使用这个行工厂,不用每次单独设置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 09:35:37