dsy19811981
2019-06-21 09:13
浏览 344

在插入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 ?

图片转代码服务由CSDN问答提供 功能建议

我发现了两种获取最后一个插入ID的方法

 结果,错误:= s.DB.ExecContext(ctx,query,qp)
if错误!= nil {
返回0,错误
} 
ID,错误:= Result.LastInsertId()
   
 
 

,另一种方法是使用mysql的

  select LAST_INSERT_ID(); 
   
  
 

这两个方法有何不同?万一第一个方法抛出错误,我该怎么办?这是否意味着我的插入操作失败了,还是意味着该方法无法返回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.

    点赞 评论

相关推荐 更多相似问题