dsy19811981 2019-06-21 09:13
浏览 592
已采纳

在插入mysql数据库时获取上次插入ID的最可靠方法是什么

I have found two way to get the last insert id

Result, err := s.DB.ExecContext(ctx, query, qp)
if err != nil {
    return 0, err
}
ID, err := Result.LastInsertId()

and another way is to use mysql's

select LAST_INSERT_ID();

How different are these two methods and what should i do in-case the first method throws an error, would it mean my insert failed or would it mean just that method failed to return the id ?

  • 写回答

1条回答 默认 最新

  • dptpn06684 2019-06-21 09:18
    关注

    Use Result.LastInsertId(). This is always reliable.

    Doing your own SELECT is not reliable, due to the way the Go driver handles pools of connection. If you do, say:

    INSERT foo INTO bar ...
    

    in one statement, then later:

    SELECT LAST_INSERT_ID();
    

    in another statement, you may get different connections to the database for each statement.

    This means your manually-selected ID may correspond with some completely unrelated INSERT statement which just happened to occur on that same connection in the past, or you may get nothing at all.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序