【问题标题】:Insert bytes in a postgresql database在 postgresql 数据库中插入字节
【发布时间】:2020-07-30 04:01:21
【问题描述】:

我正在尝试将使用 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]))

有什么想法吗?

【问题讨论】:

  • 不要将 f 字符串用于 SQL 语句。使用适当的变量替换。

标签: python postgresql file lzma


【解决方案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。

【讨论】:

  • 解决了我在回答中提到的两个问题-赞成! :)
【解决方案2】:

您的参数需要是一个元组。看这里: https://www.psycopg.org/docs/usage.html#query-parameters

第二个参数必须始终是一个序列,即使它包含一个变量:

>>> cur.execute("INSERT INTO foo VALUES (%s)", "bar")    # WRONG
>>> cur.execute("INSERT INTO foo VALUES (%s)", ("bar"))  # WRONG
>>> cur.execute("INSERT INTO foo VALUES (%s)", ("bar",)) # correct
>>> cur.execute("INSERT INTO foo VALUES (%s)", ["bar"])  # correct

顺便说一句,为什么要尝试在 Python 中将二进制数据转换为字符串?我指的是 “str(...)[2:-1]”。 我认为您需要在那里传递一个字节对象,例如:

binarystr = b"bytes here"
cur.execute("INSERT INTO foo VALUES (%s)", [binarystr])

【讨论】:

    【解决方案3】:

    感谢Alex FunkMegadest

    问题在于格式化和要格式化的变量。

    我已经解决了:

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

    【讨论】:

      猜你喜欢
      • 2015-08-16
      • 1970-01-01
      • 2012-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-29
      • 2016-05-01
      • 2013-11-21
      相关资源
      最近更新 更多