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

如何用psycopg2将Python字典插入Redshift Super类型列

用psycopg2批量插入JSON类型数据的正确方式
  • 直接插入json.dumps()转换后的字符串,会导致目标列存储普通文本,无法使用PostgreSQL的JSON属性访问(如json_col->'testdict')等操作,必须将字符串解析为JSON类型后再存储。

  • 你给出的代码中,template参数写法有误,且PostgreSQL中解析JSON字符串的标准函数是json()或jsonb()(取决于列类型是json还是jsonb),而非JSON_PARSE。修正后的代码如下:

import json
import psycopg2
import psycopg2.extras

# 假设已建立数据库连接并获取cursor
psycopg2.extras.execute_values(
    cursor,
    """
        INSERT INTO schema.table (
            id,
            col2,
            json_col
        ) 
        VALUES %s
    """,
    [(1, 2, json.dumps({'testdict': 'foobar'}))],
    template="(%s, %s, json(%s))",  # 若列类型是jsonb则改为jsonb(%s)
    page_size=800,
)
  • 更简便的方式是利用psycopg2的JSON适配器,无需手动调用json.dumps(),直接传入Python字典即可:
import psycopg2
import psycopg2.extras

# 注册JSON适配器
psycopg2.extras.register_json()

# 假设已建立数据库连接并获取cursor
psycopg2.extras.execute_values(
    cursor,
    """
        INSERT INTO schema.table (
            id,
            col2,
            json_col
        ) 
        VALUES %s
    """,
    [(1, 2, {'testdict': 'foobar'})],  # 直接传入Python字典
    template="(%s, %s, %s)",
    page_size=800,
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 05:33:29