首页 > 解决方案 > 从存储在 Python 中的 MySQL 获取最后一个插入 ID

问题描述

我正在使用 Python 中的 MySQL 连接器(Windows 上为 3.9)来调用执行插入的存储过程,但是当我尝试获取最后一个插入 ID 时,我得到 0,任何建议将不胜感激。

我在叫什么:

cursor.callproc(procedure_name, params_list)
print('last id:', cursor.lastrowid)

存储过程:

CREATE  PROCEDURE add_image_path()
BEGIN

INSERT into ImagePath values(0, "test");

END

标签: pythonstored-proceduresmysql-connector

解决方案


cursor.lastrowidmysql_insert_id()从而不是设置LAST_INSERT_ID()

您可以手动设置它LAST_INSERT_ID()

cursor.callproc(procedure_name, params_list)
cursor.execute('SELECT LAST_INSERT_ID()'))  # Add this
cursor.lastrowid = cursor.fetchone()[0]     # Add this
print('last id:', cursor.lastrowid)

https://dev.mysql.com/doc/c-api/8.0/en/mysql-insert-id.html

mysql_insert_id()在生成值的存储过程0的语句之后返回,因为在这种情况下适用于而不是过程中的语句。在过程中,您可以在 SQL 级别使用来获取值。CALLAUTO_INCREMENTmysql_insert_id()CALLLAST_INSERT_ID()AUTO_INCREMENT

LAST_INSERT_ID()和之间存在差异的原因mysql_insert_id()LAST_INSERT_ID()在脚本中易于使用,同时mysql_insert_id()尝试提供有关AUTO_INCREMENT列发生情况的更准确信息。


推荐阅读