英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论