当前位置:   article > 正文

Gorm入门-事务_global.db.transaction

global.db.transaction

参考文档 事务 | GORM - The fantastic ORM library for Golang, aims to be developer friendly.

  1. func testTransaction(GLOBAL_DB *gorm.DB) {
  2. tx := GLOBAL_DB.Begin()
  3. tx.Table("t_test_user").Where("id = ?", 4).Update("name", "111")
  4. if true {
  5. // 回滚事务
  6. //tx.Rollback()
  7. }
  8. tx.Table("t_test_user").Where("id = ?", 5).Update("name", "222")
  9. // 提交事务
  10. tx.Commit()
  11. }
  1. err = GLOBAL_DB.Transaction(func(tx *gorm.DB) error {
  2. // 在事务中执行一些 db 操作(从这里开始,您应该使用 'tx' 而不是 'db')
  3. if err := tx.Model(&TestUser{}).Where("id = ?", 4).Update("name", "11").Error; err != nil {
  4. // 返回任何错误都会回滚事务
  5. return err
  6. }
  7. if err := tx.Model(&TestUser{}).Where("id = ?", 5).Update("name", "22").Error; err != nil {
  8. return err
  9. }
  10. // 返回 nil 提交事务
  11. //return errors.New("this is a new error")
  12. return nil
  13. })
  14. fmt.Println("Transaction err:", err)
  1. func testTransactionSavePoint(GLOBAL_DB *gorm.DB) {
  2. tx := GLOBAL_DB.Begin()
  3. tx.Table("t_test_user").Where("id = ?", 4).Update("name", "77")
  4. tx.Table("t_test_user").Where("id = ?", 5).Update("name", "88")
  5. tx.SavePoint("test-point")
  6. tx.Table("t_test_user").Where("id = ?", 6).Update("name", "99")
  7. tx.RollbackTo("test-point")
  8. // 提交事务
  9. tx.Commit()
  10. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/1021967
推荐阅读
相关标签
  

闽ICP备14008679号