SQL的LAST_INSERT_ID函数总是返回0。

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

SQL Last Insert ID always return 0

问题

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

  1. checkErrorerr
  2. resulterr:= query.Exec
  3. subjectID
  4. className
  5. checkErrorerr
  6. returnIDerr:= result.LastInsertId()
  7. checkErrorerr
  8. dbSQL.Commit()

returnID始终返回0

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

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

英文:
  1. query, err := dbSQL.Prepare(`
  2. INSERT INTO class (
  3. subject_id,
  4. class_name,
  5. createAt,
  6. updatedAt,
  7. )
  8. VALUES (?, ?, NOW(), NOW())
  9. `)
  10. checkError(err)
  11. result, err := query.Exec(
  12. subjectID,
  13. className,
  14. )
  15. checkError(err)
  16. returnID, err := result.LastInsertId()
  17. checkError(err)
  18. 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:

确定