我想使用 Psycopg2 (2.7.1) copy_from() 方法将字节插入类型为 bytea
的 PostgreSQL (9.5.7) 数据库列中。
我可以使用以下代码插入我的字节:
psycopg2_cursor.copy_from(
StringIO("\x30\x40\x50"),
"my_table",
)
通过在插入后对我的表执行 SELECT,我从 bytea 列中获得了期望值:
\x304050
现在,我想在我的字节前面加上字节 0:
psycopg2_cursor.copy_from(
StringIO("\x00\x30\x40\x50"),
"my_table",
)
我收到错误:psycopg2.DataError:编码“UTF-8”的无效字节序列:0x00。根据我的理解,只有在将空字节插入文本字段时才会触发此错误,但应该按预期在 bytea 字段中工作。我错过了什么吗?有什么简单的方法可以将空字节插入到 bytea 列中吗?
谢谢!
最佳答案
https://www.postgresql.org/docs/current/static/sql-copy.html
the following characters must be preceded by a backslash if they appear as part of a column value: backslash itself, newline, carriage return, and the current delimiter character.
刚刚意识到你正在使用 COPY
,所以你必须转义反斜杠:
t=# copy b from stdin;
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself.
>> \\x00
>> \.
COPY 1
t=# copy b from stdin;
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself.
>> \x00
>> \.
ERROR: invalid byte sequence for encoding "UTF8": 0x00
CONTEXT: COPY b, line 1: "\x00"
这应该可以解决问题:
psycopg2_cursor.copy_from(
StringIO("\\x00\\x30\\x40\\x50"),
"my_table",
)
关于python - PostgreSQL - Psycopg2 - copy_from - 编码 "UTF8": 0x00 的字节序列无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44493596/