SQL的LAST_INSERT_ID函数总是返回0。

huangapple go评论81阅读模式
英文:

SQL Last Insert ID always return 0

问题

查询,错误:= dbSQL.Prepare(INSERT INTO class ( subject_id, class_name, createAt, updatedAt, ) VALUES(?,?,NOW(),NOW())

checkError(err)

result,err:= query.Exec(
	subjectID,
	className,
)

checkError(err)

returnID,err:= result.LastInsertId()

checkError(err)

dbSQL.Commit()

returnID始终返回0

注意:我的自动递增被禁用。

有什么问题吗?是因为dbSQL.Commit()result.LastInsertId()之下还是自动递增关闭导致混乱?

英文:
query, err := dbSQL.Prepare(`
		INSERT INTO class (
		    subject_id,
		    class_name,
		    createAt,
		    updatedAt,
        )
        VALUES (?, ?, NOW(), NOW())
	`)

checkError(err)

result, err := query.Exec(
	subjectID,
	className,
)

checkError(err)

returnID, err := result.LastInsertId()

checkError(err)

dbSQL.Commit()

returnID always return 0

Note: my auto increment is disable.

Whats wrong? Is it because dbSQL.Commit() is below result.LastInsertId() or auto increment off making chaos?

答案1

得分: 1

这个帖子中提到了以下建议:

> 最好的方法是使用存储过程,在存储过程中返回最后一个id

(SP: 存储过程)
Go语言示例

示例:"在执行MySQL服务器上的存储过程时如何获取lastInsertID"

这比依赖直接调用更安全,如这里所解释的

英文:

It was mentioned in this thread, with, as advice:

> It is better idea to use an SP and in this SP return the last id

(SP: Stored Procedure)
Example in Go.

Example: "How to get lastInsertID when executing a Stored Procedure on a mySQL Server"

That would be safer than relying on a direct call, as explained here.

huangapple
  • 本文由 发表于 2021年10月4日 12:26:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/69430905.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定