我正在尝试使用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)就不能给出一个“简单”的值列表/元组吗?
executemany()
接受参数列表,每个参数都应该是一个与execute()
一起工作的对象,即tuple
或dict
,但不是一个简单的值,如数字或字符串。这就是为什么第二个版本是可以的:您正在生成多个dict
s其中列表中的每个元素都是一个
tuple
。executemany
需要序列,例如列表列表:相关问题 更多 >
编程相关推荐