使用简单列表执行psycopg2?

2024-04-25 20:47:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用psycopg2 executemany进行简单的多次插入,但我只能使用dict而不是“简单”的值序列:

# given:
values = [1, 2, 3] ; cursor = conn.cursor()

# this raises TypeError: 'int' object does not support indexing:
cursor.executemany('INSERT INTO t (col_a) VALUES ( %s )', values)
# I also tried encapsulating my 'values' into a tuple/list but it gives another exception (TypeError: not all arguments converted during string formatting).

# while this is ok:
cursor.executemany('INSERT INTO t (col_a) VALUES ( %(value)s )', [  dict(value=v) for v in values ])

不使用“named”参数(%(value)s)就不能给出一个“简单”的值列表/元组吗?


Tags: valuenot序列colthiscursorpsycopg2dict
2条回答

executemany()接受参数列表,每个参数都应该是一个与execute()一起工作的对象,即tupledict,但不是一个简单的值,如数字或字符串。这就是为什么第二个版本是可以的:您正在生成多个dicts

values = [(1,), (2,), (3,)]

其中列表中的每个元素都是一个tuple

executemany需要序列,例如列表列表:

[[v] for v in values]

相关问题 更多 >