使用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.
相关产品推荐
相关产品推荐

