首页 > 解决方案 > 在 postgresql 数据库中插入字节

问题描述

我正在尝试将使用 lzma 压缩的文件插入到带有 bytea 字段的 postgresql 表中。问题是它无法格式化字符串并发生此错误:

TypeError: not all arguments converted during string formatting

要将数据插入数据库,我使用的是 psycopg2:

CUR.execute(f"""INSERT INTO table (id, date, bytes) """ + """VALUES ("{file_name}", CURRENT_DATE, %s""", (str(compress(file.read()))[2:-1]))

有任何想法吗?

标签: pythonpostgresqlfilelzma

解决方案


很难说,没有最小的可重复样本,但也许这样:

CUR.execute(f"""INSERT INTO table (id, date, bytes) VALUES (%s, CURRENT_DATE, %s""", (file_name, compress(file.read()))[2:-1])

请注意,所有变量都在 %s 中,这是 psycopg2 需要的。{file_name} 符号用于格式函数,此处未使用。您不需要引号,psycopg2 会为您处理。bytea Postgres 类型需要一个缓冲区 python 类型,所以我删除了 str.


推荐阅读