从 executemany 语句中获取 'return' 值

Fetch a 'return'd value from an executemany statement

将 Postgresql 9.5 与 psycopg2 结合使用。

使用 'returning',我可以检索我插入的单个行的 'id'。

sql = "insert into %s (%s) values (%s) returning id" % (table_name, columns, values_template)        
values = tuple(row_dict[key] for key in keys)
cur.execute(sql, values)
id_new_row = cur.fetchone()[0]

我还希望检索使用 executemany 语句插入的许多行中最后一行的 ID。

cur.executemany(insert_sql , data_dict)
#get id of the last row inserted
id_new_row = cur.fetchone()[0]

但这会引发数据库错误,"no results to fetch"。

这是根本不可能完成的事情,还是我要求的结果不正确?

我认为你想做的事情是不可能的。

首先,就 PEP 249 而言,您已经处于危险的境地。具体来说,它是关于 executemany 的。

Use of this method for an operation which produces one or more result sets constitutes undefined behavior, and the implementation is permitted (but not required) to raise an exception when it detects that a result set has been created by an invocation of the operation.

如果您查看 psycopg2 源代码,您会发现 executemany 设置了 no_result 标志。当您追踪到 code that handles the query 时,您可以看到它丢弃了所有结果(发布时的第 1582-1595 行)。