psycopg2 executemany with simple list?

ε祈祈猫儿з 提交于 2019-12-10 22:07:06

问题


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

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


回答1:


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

[[v] for v in values]



回答2:


executemany() takes a list of parameters and each single parameter should be an object that works with execute(), i.e., a tuple or a dict, but not a simple value like a number or string. That's why the second version is OK: you're generating multiple dicts. You can also just write:

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

where each element of the list is a tuple.



来源:https://stackoverflow.com/questions/19154324/psycopg2-executemany-with-simple-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!