从存储在 Python 中的 MySQL 中获取最后一个插入 ID

Getting last insert id from MySQL stored in Python

我正在使用 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

cursor.lastrowid 是从 mysql_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() returns 0 following a CALL statement for a stored procedure that generates an AUTO_INCREMENT value because in this case mysql_insert_id() applies to CALL and not the statement within the procedure. Within the procedure, you can use LAST_INSERT_ID() at the SQL level to obtain the AUTO_INCREMENT value.

The reason for the differences between LAST_INSERT_ID() and mysql_insert_id() is that LAST_INSERT_ID() is made easy to use in scripts while mysql_insert_id() tries to provide more exact information about what happens to the AUTO_INCREMENT column.