Python SQLAlchemy 插入后获取返回的 ID

11

我想在使用SQLAlchemy插入postgresql后获取最后插入记录的ID。以下是代码,

insert_record = {list of data}
result = connection.execute(tbl_example.insert().returning(tbl_example.c.id), insert_record)
print result.id

插入操作运行良好,但我似乎无法获得最后插入的ID,我收到以下错误信息:
'ResultProxy'对象没有'id'属性
返回对象中的返回ID位于何处?
1个回答

11

它直接位于返回的对象中。这是来自文档的示例:

stmt = table.update().\
          where(table.c.data == 'value').\
          values(status='X').\
          returning(table.c.server_flag,
                    table.c.updated_timestamp)

for server_flag, updated_timestamp in connection.execute(stmt):
    print(server_flag, updated_timestamp)

此外,ResultProxy 支持通过位置(如示例所示)和名称访问。因此,您可以使用类似于 row_id = row['id'] 的语句,其中:

for row in connection.execute(stmt):
    row_id = row['id']
    row_id = row.id
    row_id = row[0]
    print(row_id)

请注意,并非所有数据库后端都支持此功能。从文档中可以看到:

请注意,并非所有数据库/DBAPI都支持RETURNING。对于那些不支持的后端,在编译和/或执行时会引发异常。


2
类似row_id = result['id']这样的语句会导致错误,如下所示:TypeError: 'ResultProxy' object has no attribute '__getitem__' - rksh
这个答案是正确的,文档也很好,并且有很好的解释。它应该被设置为正确的答案,不应该被投票下降。@rksh,你需要先迭代execute(stmt)返回的内容。像for result in connection.execute(stmt): row_id = result['id'] 这样做。你也可以使用 row_id = result.id - André C. Andersen
1
我对这个答案唯一的困惑是关于update()部分。我期望看到像这里中的insert()(仍然是我的+1)。 - minus one

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接