gpt4 book ai didi

Python mysql.connector cursor.lastrowid 总是返回 0

转载 作者:太空狗 更新时间:2023-10-29 22:22:16 27 4
gpt4 key购买 nike

我正在使用 Python 2.7 的 mysql.connector 模块。我已将我的代码分解为最简单的脚本,但我仍然遇到这个问题。问题是,当我尝试获取最后一行 ID(在 MySQL 中为 LAST_INSERT_ID)时,无论插入了多少行,我都会返回 0。有人能解决这个问题吗?

我的代码如下:

import mysql.connector
default_config = {
'user': 'root',
'password': 'password',
'host': '127.0.0.1',
'database': 'test',
'raise_on_warnings': True,
'autocommit': True
}
connection = mysql.connector.connect(**default_config)
cursor = connection.cursor()
args = ('name', 'desc')
cursor.callproc('sp_tools_insert', args)
lastid = cursor.lastrowid
print lastid # This returns 0 every time, regardless of number of inserts

我的存储过程是这样的:

CREATE PROCEDURE `sp_tools_insert`
(
IN p_name VARCHAR(45),
IN p_description VARCHAR(255)
)
BEGIN
INSERT INTO TOOLS
(
tool_name,
description
)
VALUES
(
p_name,
p_description
);
END

我的 TOOLS 表是这样定义的:

DROP TABLE IF EXISTS `test`.`TOOLS` ;

CREATE TABLE IF NOT EXISTS `test`.`TOOLS` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`tool_name` VARCHAR(45) NOT NULL,
`description` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;

我已验证存储过程正常工作并且 .callproc() 调用按预期工作。唯一不起作用的是 .lastrowid 调用。有什么建议吗?

最佳答案

lastrowid属性:

… returns the value generated for an AUTO_INCREMENT column by the previous INSERT or UPDATE statement …

而且您还没有运行 INSERTUPDATE 语句,您运行了 CALL 语句。

要获取详细信息,您必须点击 mysql_insert_id 的 C API 文档链接。 lastrowid 调用的函数。特别是:

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.

我在这里假设您的 TOOLS 表实际上确实有一个 AUTO_INCREMENT 列;否则,一开始就没有任何值(value)。

另外,请注意,这只是其中一种方式,与您的断言相反,lastrowidLAST_INSERT_ID() 不是一回事。值得阅读 LAST_INSERT_ID 的文档

关于Python mysql.connector cursor.lastrowid 总是返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27260363/

27 4 0
文章推荐: c# - Angular 在 ASP.NET MVC 之上,显示错误
文章推荐: c# - 我可以使用 Json.net 在一次操作中将嵌套属性序列化到我的类吗?
文章推荐: c# - 如何在 C# 中比较两个 list 并只保留没有重复的项目?