当前位置: > > > > 如何从sqlx获取最后插入行的id?
来源:stackoverflow
2024-04-24 14:36:34
0浏览
收藏
IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天给大家整理了《如何从sqlx获取最后插入行的id?》,聊聊,我们一起来看看吧!
问题内容
我想使用 sqlx
取回插入 mysql 数据库的最后一篇文章的 id:
resultpost, err := shared.dbmap.exec("insert into post (user_id, description, link) values (?, ?, ?)", userid, title, destpath) if err != nil { log.println(err) c.json( http.statusinternalservererror, gin.h{"error": "internal server error"}) } fmt.println("resultpost is:", resultpost)
问题在于 resultpost
被打印为对象:
resultPost is: {0xc420242000 0xc4202403a0}
所以我想知道提取刚刚插入的行的 id 的正确方法是什么?
解决方案
看起来你只需要:
resultpost.lastinsertid()
更多信息,请在中搜索lastinsertid
exec
, 的返回值并不意味着可以直接访问——它是一个有两个方法可以调用的对象,其中之一是lastinsertid( )
。
lastId, err := resultPost.LastInsertId() if err != nil { panic(err) } fmt.Println("LastInsertId: ", lastId)
终于介绍完啦!小伙伴们,这篇关于《如何从sqlx获取最后插入行的id?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~公众号也会发布Golang相关知识,快来关注吧!