登录
首页 >  Golang >  Go问答

golang中的事务使用方法解析

来源:stackoverflow

时间:2024-02-07 13:18:22 253浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《golang中的事务使用方法解析》,聊聊,我们一起来看看吧!

问题内容

我有一个代码插入到数据库

这是我的模型:

func (samethodattach *Product_gallery) SaveGalleri(db *gorm.DB) (*Product_gallery, error) {
    var err error
    err = db.Debug().Create(&samethodattach).Error
    if err != nil {
        return &Product_gallery{}, err
    }
    return samethodattach, nil
}

我想在插入中使用事务。


正确答案


对此有一些要点:

如果不需要,您可以在初始化时禁用它,之后您将获得约 30%+ 的性能提升。

// globally disable
db, err := gorm.open(sqlite.open("gorm.db"), &gorm.config{
  skipdefaulttransaction: true,
})

// continuous session mode
tx := db.session(&session{skipdefaulttransaction: true})
tx.first(&user, 1)
tx.find(&users)
tx.model(&user).update("age", 18)

一般流程在事务中执行一组操作:

db.transaction(func(tx *gorm.db) error {
  // do some database operations in the transaction (use 'tx' from this point, not 'db')
  if err := tx.create(&animal{name: "giraffe"}).error; err != nil {
    // return any error will rollback
    return err
  }

  if err := tx.create(&animal{name: "lion"}).error; err != nil {
    return err
  }

  // return nil will commit the whole transaction
  return nil
})

gorm也支持手动事务,gorm提供了savepointrollbackto来保存点并回滚到某个保存点,例如:像这样:

// begin a transaction
tx := db.begin()

// do some database operations in the transaction (use 'tx' from this point, not 'db')
tx.create(...)

// ...

// rollback the transaction in case of error
tx.rollback()

// or commit the transaction
tx.commit()
func CreateAnimals(db *gorm.DB) error {
  // Note the use of tx as the database handle once you are within a transaction
  tx := db.Begin()
  defer func() {
    if r := recover(); r != nil {
      tx.Rollback()
    }
  }()

  if err := tx.Error; err != nil {
    return err
  }

  if err := tx.Create(&Animal{Name: "Giraffe"}).Error; err != nil {
     tx.Rollback()
     return err
  }

  if err := tx.Create(&Animal{Name: "Lion"}).Error; err != nil {
     tx.Rollback()
     return err
  }

  return tx.Commit().Error
}

今天关于《golang中的事务使用方法解析》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>