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

Viewed 1687

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 Answers

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.

Related