gpt4 book ai didi

python - 使用 cursor.mogrify 将元组列表中的行插入数据库会出错

转载 作者:行者123 更新时间:2023-11-29 12:30:45 25 4
gpt4 key购买 nike

我正在尝试使用这个 psycopg2: insert multiple rows with one query 使用 cursor.mogrify 将大量行插入到 postgres 中

数据是一个元组列表,其中每个元组是需要插入的一行。

 cursor = conn.cursor()

args_str = ','.join(cursor.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in data)

cursor.execute(
"insert into table1 (n, p, r, c, date, p1, a, id) values " + args_str)`

但出现错误:

TypeError: sequence item 0: expected str instance, bytes found

在线:

  args_str = ','.join(cursor.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in data)

如果我尝试更改为 b''.join(cursor.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s)", x) 对于数据中的 x) ,然后执行查询给出插入字节的错误....

我做错了什么吗?

最佳答案

data = [(1,2),(3,4)]
args_str = ','.join(['%s'] * len(data))
sql = "insert into t (a, b) values {}".format(args_str)
print (cursor.mogrify(sql, data).decode('utf8'))
#cursor.execute(sql, data)

输出:

insert into t (a, b) values (1, 2),(3, 4)

关于python - 使用 cursor.mogrify 将元组列表中的行插入数据库会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41999354/

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