我正在尝试生成自动查询。 我想使用executemany,但我需要使用returning语句,所以我做了这个:
def format_bind(cols, rows):
return '(' + '), ('.join([', '.join(['%s'] * cols)] * rows) + ')'
def insert_many(table, values, id_column):
if not values:
return []
keys = values[0].keys()
conn = psycopg2.connect("dbname='db' user='postgres' host='localhost' password='postgres'")
cursor = conn.cursor()
query = cursor.mogrify("INSERT INTO {} ({}) VALUES {} RETURNING {}".format(table,
', '.join(keys),
format_bind(len(keys), len(values)),
id_column),
[tuple(v.values()) for v in values])
cursor.execute(query)
return [t[0] for t in (cursor.fetchall())]
问题是当我执行它时,会收到:
error list index out of range
。有人能帮我解决吗?