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

使用psycopg+unnest更新bytea列时遇AttributeError问题求助

问题原因及解决办法

问题原因

在psycopg 3.x版本中,当你把包含bytes类型(对应PostgreSQL的bytea)的列表作为unnest的参数传递时,psycopg的默认类型适配逻辑会将bytes对象转换为memoryview以优化性能。但在处理unnest的参数解析流程中,内部代码尝试对memoryview对象调用join方法,而memoryview并没有这个属性,因此抛出AttributeError。

常规单条更新或executemany方式不会触发该问题,因为这类场景是逐个处理参数,类型适配的路径与unnest批量更新不同。

解决办法

方法1:用Binary包装bytea数据

导入psycopg的Binary类型,将每个feat字段的bytes数据包装起来,让psycopg明确识别为bytea类型,避免转换为memoryview。修改后的代码如下:

import numpy as np
from psycopg.types.binary import Binary

data = [(Binary(np.random.random(20).tobytes()), i) for i in range(100)]
cursor.execute(
    """
    UPDATE my_table
    SET feat = s.feat
    FROM unnest(%s) s(feat bytea, id integer)
    WHERE id = s.id;
    """, (data,),
)

方法2:改用executemany(适合数据量不大的场景)

如果数据规模不是特别大,也可以回到常规批量更新方式,虽然性能略逊于unnest,但能避开类型适配问题:

import numpy as np

data = [(np.random.random(20).tobytes(), i) for i in range(100)]
cursor.executemany(
    """
    UPDATE my_table
    SET feat = %s
    WHERE id = %s;
    """, data
)

内容的提问来源于stack exchange,提问作者Yohann L.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 17:20:45