本文介绍了psycopg2 executemany 带有简单列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在尝试使用 psycopg2 executemany 进行简单的多插入,但我只能使用 dict 而不是普通"值序列使其工作:

I'm trying to use psycopg2 executemany for a simple multi-insert but I can only make it work using dict and not "plain" sequence of values:

# 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 ])

是否可以在不使用命名"参数 (%(value)s) 的情况下给出简单"的值列表/元组?

isn't it possible to give a "simple" list/tuple of values without using "named" parameter (%(value)s) ?

推荐答案

executemany 需要一个序列序列,例如.列表列表:

executemany expects a sequence of sequences, eg. a list of lists:

[[v] for v in values]

这篇关于psycopg2 executemany 带有简单列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 20:23