psycopg2 executemany with simple list?

gst picture gst · Oct 3, 2013 · Viewed 14.9k times · Source

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

Answer

Janne Karila picture Janne Karila · Oct 3, 2013

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

[[v] for v in values]