Python Sqlite。插入后如何获取自动增量主键的值,而不是last_insert_rowid()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3442033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sqlite. How to get value of Auto Increment Primary Key after Insert, other than last_insert_rowid()?
提问by Jon Cox
I am using Sqlite3 with Flask microframework, but this question concerns only the Sqlite side of things..
我在 Flask 微框架中使用 Sqlite3,但这个问题只涉及 Sqlite 方面的事情..
Here is a snippet of the code:
这是代码的一个片段:
g.db.execute('INSERT INTO downloads (name, owner, mimetype) VALUES (?, ?, ?)', [name, owner, mimetype])
file_entry = query_db('SELECT last_insert_rowid()')
g.db.commit()
The downloadstable has another column with the following attributes: id integer primary key autoincrement,
该downloads表还有另一列具有以下属性: id integer primary key autoincrement,
If two people write at the same time the code above could produce errors.
如果两个人同时编写,上面的代码可能会产生错误。
Transactions can be messy. In Sqlite is there a neat built in way of returning the primary key generated after doing an INSERT ?
交易可能很混乱。在 Sqlite 中是否有一种巧妙的内置方式来返回执行 INSERT 后生成的主键?
采纳答案by reko_t
The way you're doing it is valid. There won't be a problem if the above snipped is executed concurrently by two scripts. last_insert_rowid()returns the rowid of the latest INSERT statement for the connection that calls it. You can also get the rowid by doing g.db.lastrowid.
你这样做的方式是有效的。如果上面的snippet由两个脚本同时执行,就不会有问题。last_insert_rowid()返回调用它的连接的最新 INSERT 语句的 rowid。您还可以通过执行g.db.lastrowid.

