2013-10-03 3 views
2

나는 간단한 다중 삽입에 대한 psycopg2 executemany를 사용하기 위해 노력하고있어하지만 난 단지 그것을 DICT를 사용하여 작업 할 수없는 가치 "일반"순서 :간단한 목록이있는 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 ]) 

는 "는 제공 할 수 없습니다 "명명 된"매개 변수 (% (value) s)를 사용하지 않고 값의 단순한 "list/tuple?

답변

3

executemany은 시퀀스 시퀀스를 기대합니다. 리스트 목록 :

[[v] for v in values] 
+0

Janne & Fog에게 감사의 말을 전하겠습니다. – gst

2

executemany() 파라미터들의리스트를 얻어, 각 싱글 파라미터 execute(), 숫자 또는 문자열과 같은 즉, tuple 또는 dict 아니라 간단한 값 작동 목적이어야한다. 두 번째 버전이 OK 인 이유는 복수형 dict을 생성하기 때문입니다. 다음과 같이 쓸 수도 있습니다.

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

여기에서 목록의 각 요소는 tuple입니다.