python - PostgreSQL - Psycopg2 - copy_from - 编码 "UTF8": 0x00 的字节序列无效

标签 python postgresql psycopg2

我想使用 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/

相关文章:

python + psycopg2 = 未知类型?

python - Psycopg DB - 向代码添加持久性时出错

python - 如何使用 psycopg2 在 postgres 中获取表?

python - Pyplot 图例索引错误 : tuple index out of range

python - 在Python中将文件直接上传到FTP服务器

python - 简单的 Python 代码,带有奇怪的列表操作/理解技术,列表的一个元素被分配给一个变量

linux - 使用 psycopg2 时重新声明游标会创建新连接吗?

sql - PostgreSQL,从 2 个表中选择,但仅从表 2 中选择最新元素

python - 使用 Python(漂亮的汤)抓取需要单击 "I agree to cookies"按钮的网页?

postgresql - 查询时首先返回带空列的行(列 =?或列为空)