简体   繁体   English

SQL 最后插入 ID 始终返回 0

[英]SQL Last Insert ID always return 0

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 returnID始终返回 0

Note: my auto increment is disable.注意:我的自动增量是禁用的。

Whats wrong?怎么了? Is it because dbSQL.Commit() is below result.LastInsertId() or auto increment off making chaos?是因为dbSQL.Commit()低于result.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 并在此 SP 中返回最后一个 id

(SP: Stored Procedure) (SP:存储过程)
Example in Go . Go 中的示例

Example: " How to get lastInsertID when executing a Stored Procedure on a mySQL Server "示例:“lastInsertID服务器上执行存储过程时如何获取 lastInsertID

That would be safer than relying on a direct call, as explained here .这比依赖直接调用更安全,如此处所述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM