2013-10-03 116 views
2

我試圖使用psycopg2 executemany一個簡單的多插入,但我只能使其工作字典使用,而不是「普通」值序列:psycopg2 executemany與簡單列表?

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

回答

3

executemany期望序列的序列,例如,列表的列表:

[[v] for v in values] 
+0

好在謝謝Janne&Fog我現在看到它。 – gst

2

executemany()需要的參數的列表和每個單獨的參數應該是與​​,即tupledict,但不是一個簡單的值如數字或字符串工作的對象。這就是爲什麼第二個版本是好的:你生成多個dict。您也可以只寫:

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

其中列表中的每個元素都是tuple