Gorm: how to get the LastInsertId after calling Exec

Created on 8 Oct 2014  路  6Comments  路  Source: go-gorm/gorm

how to get the LastInsertId after calling Exec?
in another word how to grab sql.Result after calling Exec

All 6 comments

After an object saved, you could use the object's ID as LastInsertId, and it compatible with all databases. (LastInsertId doesn't works with postgres)

db.Save(&user); 
fmt.Println(user.Id)

And you could access the RowsAffected like this:

db.Where("xxx").Update("age", "1").RowsAffected

So sounds to me, it is not necessary to access the sql.Result?

hmm, i know that Create or Save would do the trick. im just thinking if im doing a custom sql execution with gorm using Exec, there is just no way to get the LastInsertId. would be good to offer this flexibility i.e. access to the sql.Result of the Exec command.
i just find this rather limiting and inflexible.
its a great suggestion on what gorm can implement next.

@jinzhu i really think the Exec should return sql.Result
currently there is too many limitation with the db.Create() function
as such returning the LastInsertId is just too impossible.
its impossible to use the sql NOW() as default value in the struct field, which is a requirement on most time sensitive insertion process. unless this feature is in, i think getting the LastInsertId is just impossible.

@badoet how do you solve this problem??

@stevenkitter see the answer above. you cant use custom sql query. im not using this library anymore.
i switched to https://github.com/go-pg/pg

Yeah there is a possibility that to get spatial data working with this library in MySQL I have to use the raw SQL with exec to insert a row of data. But then I run into this problem. I hope this is resolved with Gorm 2.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

easonlin404 picture easonlin404  路  3Comments

hypertornado picture hypertornado  路  3Comments

koalacxr picture koalacxr  路  3Comments

superwf picture superwf  路  3Comments

Ganitzsh picture Ganitzsh  路  3Comments