python - 从存储在 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
解决方案
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()
在生成值的存储过程0
的语句之后返回,因为在这种情况下适用于而不是过程中的语句。在过程中,您可以在 SQL 级别使用来获取值。CALL
AUTO_INCREMENT
mysql_insert_id()
CALL
LAST_INSERT_ID()
AUTO_INCREMENT
LAST_INSERT_ID()
和之间存在差异的原因mysql_insert_id()
是LAST_INSERT_ID()
在脚本中易于使用,同时mysql_insert_id()
尝试提供有关AUTO_INCREMENT
列发生情况的更准确信息。
推荐阅读
- node.js - 返回填充的项目匹配条件
- reactjs - 材料表如何选择一行在选择时更改背景颜色
- javascript - 在 javascript 中使用正则表达式过滤字符串
- opengl - Opengl 立方体贴图 - freeimage 和 stb 图像库的不同结果
- java - 在 Streams 中使用 Optional
- c# - 将 blazor ComponentBase 渲染为字符串
- google-kubernetes-engine - GKE Menu 界面工作负载持续交付
- python - 重复键更新上的 SQLAlchemy MySQL
- php - PDO lastInsertID() 由于在单个调用中运行多个查询而失败
- php - 如何在不使用 json_decode($object, true) 函数的情况下手动将对象转换为数组?