带有 pg8000 的 PostgreSQL - INSERT 结果从 SQL 到另一个 table

PostgreSQL wiht pg8000 - INSERT results from an SQL to another table

我正在尝试将行从 PostgreSQL table 复制到另一个,使用 Python 的 pg8000 驱动程序。这是代码:

import pg8000
conn = pg8000.connect(user="postgres", password="XXXXX",database="test")
cursor = conn.cursor()
cursor.execute("SELECT * FROM exampletable")
results = cursor.fetchall()

我现在想要的是将结果完全插入一个新的table。它应该是这样的:

cursor.executemany("INSERT INTO secondtable VALUES (%s)", results)

但不是这样运行的,我不知道如何修复它。并非所有字段都是字符串类型,也许应该以某种方式修复?

格式 %s 用于标量值。将结果转换为字符串,如下所示:

cursor.execute("INSERT INTO secondtable VALUES %s" % str(results))

稍微偏离主题,但搜索相关问题会引导到这里。我想知道如何格式化 execute sql 字符串的绑定变量。 koriander 的回答中给出的格式不适用于 pg8000 1.10.5。这是最终对我有用的东西:

    some_field_value = 'value'
    sql = 'SELECT a_field FROM your_table WHERE some_field = %s'
    cursor.execute(sql, [some_field_value])

来自文档的详细信息:pg8000 Cursor.execute

重要的一点:

args – If paramstyle is qmark, numeric, or format, this argument should be an array of parameters to bind into the statement

请记住两点:

  1. pg8000 从不接受格式字符串周围的引号 (%s)
  2. pg8000.paramstyle 的值很重要。默认值为 'format'