如何使用beego/orm解决’no LastInsertId available’的问题?

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

How to work around 'no LastInsertId available' using beego/orm

问题

我正在尝试使用https://github.com/astaxie/beego/tree/master/orm将一个struct插入到PostgreSQL数据库中。这个操作应该很简单。

  1. import "github.com/astaxie/beego/orm"
  2. type Product struct {
  3. ID string `orm:"pk"`
  4. ...
  5. }
  6. product := &Product{ID: productID}
  7. _, err := orm.NewOrm().Insert(product)
  8. if err != nil {
  9. log.Fatal(err)
  10. }

每当代码运行时,我一直收到no LastInsertId available的错误(插入操作本身是成功的),但是程序崩溃了。
我理解这是由于我使用了https://www.github.com/lib/pq驱动程序,而它受到PostgreSQL的限制。

有没有办法使用beego/orm解决这个问题?

英文:

I am trying to use https://github.com/astaxie/beego/tree/master/orm to insert a struct into a postgres database. The operation should be simple

  1. import "github.com/astaxie/beego/orm"
  2. type Product struct {
  3. ID string `orm:"pk"`
  4. ...
  5. }
  6. product := &Product{ID: productID}
  7. _, err := orm.NewOrm().Insert(product)
  8. if err != nil {
  9. log.Fatal(err)
  10. }

I keep getting this; no LastInsertId available whenever the code runs (the insert is otherwise successful) but I get a crash.
I understand is it due to postgresql limitations because I use https://www.github.com/lib/pq driver.

Is there I way to work around this using beego/orm?

答案1

得分: 1

如果崩溃是由于你的log.Fatal(err)引起的,你可以通过检查和避免它来避免这种情况:

  1. _, err := orm.NewOrm().Insert(product)
  2. if err != nil {
  3. if err.Error() == "no LastInsertId available" {
  4. log.Println(err)
  5. } else {
  6. log.Fatal(err)
  7. }
  8. }
英文:

If the crash is being caused by your log.Fatal(err), you can avoid this by checking and avoiding it:

  1. _, err := orm.NewOrm().Insert(product)
  2. if err != nil {
  3. if err.Error() == "no LastInsertId available" {
  4. log.Println(err)
  5. } else {
  6. log.Fatal(err)
  7. }
  8. }

huangapple
  • 本文由 发表于 2017年8月22日 08:17:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/45807184.html
匿名

发表评论

匿名网友

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

确定