2016-09-30 29 views
0

我想在使用SQLAlchemy插入postgresql後獲取最後插入的記錄的ID。下面是代碼,Python SQLAlchemy在插入後得到重調ID

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

的插入確實不錯,但我似乎無法得到最後插入,我得到以下錯誤的ID,

AttributeError: 'ResultProxy' object has no attribute 'id'

哪裏返回ID位於返回的對象?

回答

0

它直接位於返回對象中。有例如由documentation:

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) 

此外,ResultProxysupports經由當前位置訪問(如實施例中),並通過名稱。所以,你可以使用類似於:row_id = result['id']

+0

像'''row_id = result ['id']'''給了我這樣的錯誤''TypeError:'ResultProxy'對象沒有屬性'__getitem __''''' – rksh

相關問題