我正在使用 Python 在 Google App Engine 上构建一个使用 mysql 的应用程序。当我在具有自动增量的表中插入新行时,我需要检索自动生成的 ID。有几篇文章(包括以下两篇文章)建议使用“SELECT LAST_INSERT_ID();”,但这不起作用。
PHP/MySQL insert row then get 'id'
Query-getting last inserted row id in mysql using query
使用该命令时我得到的是所有 ID 中的第一个。我的代码如下所示:
cursor.execute("INSERT INTO tablename (val1, val2) VALUES ("foobar", 42);")
last_id = cursor.execute("SELECT LAST_INSERT_ID();")
还有其他方法可以做到这一点吗?
最佳答案
SQL 正确,但 Python 不正确。 cursor.execute()
返回受影响的行数,而不是操作结果。您需要调用 cursor.fetchone()
来获取实际结果,该结果将是一个元组。
关于python - 在 Google App Engine 上的 Mysql 中插入行后获取 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29989623/