2013-10-03 40 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