python - 在 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]))
有任何想法吗?
解决方案
很难说,没有最小的可重复样本,但也许这样:
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.
推荐阅读
- javascript - 使用 node.js 从 Google Cloud 函数中的 IncomingMessage 对象读取正文
- scala - scala:为什么代码返回 List [Any] 而不是 List [String]?
- android - java命令在Android中位于哪里?
- angular - 尝试在服务外使用 forEach() 或 map() 时,subscribe() 内的数组为空,但在服务中填充
- google-cloud-platform - 坚持将 GCP 项目转移到组织
- c# - 如何从文本中制作一个自动空白框?
- python - 未创建通过循环的列表
- flutter - Flutter/Dart:连接整数
- oracle - Docker 中的 Logstash 没有响应
- asp.net-core - 谷歌云 ASP.NET Core 应用程序