3

我正在尝试从带有 sqlite 的 sqlalchemy 插入中获取最后插入的行 ID。看起来这应该很容易,但我还没有设法弄清楚,到目前为止在我的搜索中没有找到任何东西。我是 python 新手,我知道有一些类似的帖子,所以我希望这不是重复。下面是一些简单的示例脚本:

from sqlalchemy import *    
engine = create_engine('sqlite:///myTest.db',echo=False)
metadata = MetaData()

dbTable1 = Table('dbTable1', metadata,Column('ThisNum', Integer),Column('ThisString', String))
metadata.create_all(engine)
dbConn = engine.connect()

insertList={}
insertList['ThisNum']=1
insertList['ThisString']='test'
insertStatement = dbTable1.insert().values(insertList)
lastInsertID = dbConn.execute(insertStatement).inserted_primary_key

返回的值为空。我得到相同的结果使用

lastInsertID = dbConn.execute(insertStatement).last_inserted_ids()

我可以在插入后使用单独的语句获取最后一个 rowid:

lastInsertID = dbConn.execute('SELECT last_insert_rowid();')

但这不能保证在两次执行之间没有访问数据库,因此返回的 ID 可能不正确。最后,我尝试在一次执行中执行插入和选择语句,例如:

lastInsertID = dbConn.execute('INSERT INTO "dbTable1" ("ThisNum", "ThisString") VALUES (1, "test"); SELECT last_insert_rowid();')

但这给出了错误:sqlite3.Warning:您一次只能执行一条语句。

任何帮助,将不胜感激。谢谢。

4

0 回答 0