在使用原始查询时,如何在Golang的Go ORM中检索最后插入的ID?

huangapple go评论136阅读模式
英文:

How to retrieve last inserted ID in golang go orm when using Raw query

问题

我正在使用原始查询在MySQL中创建一个条目,

db.Exec("INSERT STATEMENT")

我想要检索最后一个ID,在原生的golang/sql包中很容易,但是在GORM中我看不到任何东西

我知道使用db.Create可以解决我的问题,但我必须使用原始查询,而不是其他方法。

英文:

I am using a raw query to create an entry in MySQL,

db.Exec("INSERT STATEMENT")

I want to retrieve the last ID , in the native golang/sql package, it is easy, but here in GORM I can't see anything

> I know that using the db.Create can solve my problem, but I have to use Raw query and nothing else

答案1

得分: 3

你为什么要使用 GORM,而实际上并没有使用 GORM,而是使用原始查询呢?GORM 通过 DB 方法公开了通用数据库接口。所以你可以这样做:

sqlDB, err := db.DB()

res, err := sqlDB.Exec("INSERT STATEMENT")

lid, err := res.LastInsertId()

当然,你应该处理可能出现的错误。

英文:

Why do you want to do it with GORM if you are not actually using GORM, but a raw query anyway? GORM exposes the generic database interface through the DB method. So you can do this:

sqlDB, err := db.DB()

res, err := sqlDB.Exec("INSERT STATEMENT")

lid, err := res.LastInsertId()

Of course, you should handle possible errors.

huangapple
  • 本文由 发表于 2021年5月28日 16:00:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/67735044.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定