使用 cursor.mogrify 从元组列表中将行插入 db 会出现错误 [英] Inserting rows into db from a list of tuples using cursor.mogrify gives error

查看:63
本文介绍了使用 cursor.mogrify 从元组列表中将行插入 db 会出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用这个 psycopg2:用一个查询插入多行

data 是一个元组列表,其中每个元组是需要插入的一行.

data is a list of tuples where each tuple is a row that needs to be inserted.

 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) ,然后执行查询给出插入字节的错误....

If I try to change to b''.join(cursor.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in data) , then execute query gives error for inserting byte....

我做错了吗?

推荐答案

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)

这篇关于使用 cursor.mogrify 从元组列表中将行插入 db 会出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆