gpt4 book ai didi

python - 带有 pg8000 的 PostgreSQL - 将 SQL 的结果插入到另一个表

转载 作者:太空宇宙 更新时间:2023-11-04 03:37:16 25 4
gpt4 key购买 nike

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

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

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

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

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

最佳答案

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

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

关于python - 带有 pg8000 的 PostgreSQL - 将 SQL 的结果插入到另一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28399053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com