赞
踩
参考文档 事务 | GORM - The fantastic ORM library for Golang, aims to be developer friendly.
- func testTransaction(GLOBAL_DB *gorm.DB) {
- tx := GLOBAL_DB.Begin()
- tx.Table("t_test_user").Where("id = ?", 4).Update("name", "111")
- if true {
- // 回滚事务
- //tx.Rollback()
- }
- tx.Table("t_test_user").Where("id = ?", 5).Update("name", "222")
- // 提交事务
- tx.Commit()
- }
-
- err = GLOBAL_DB.Transaction(func(tx *gorm.DB) error {
- // 在事务中执行一些 db 操作(从这里开始,您应该使用 'tx' 而不是 'db')
-
- if err := tx.Model(&TestUser{}).Where("id = ?", 4).Update("name", "11").Error; err != nil {
- // 返回任何错误都会回滚事务
- return err
- }
-
- if err := tx.Model(&TestUser{}).Where("id = ?", 5).Update("name", "22").Error; err != nil {
- return err
- }
-
- // 返回 nil 提交事务
- //return errors.New("this is a new error")
- return nil
- })
- fmt.Println("Transaction err:", err)
- func testTransactionSavePoint(GLOBAL_DB *gorm.DB) {
- tx := GLOBAL_DB.Begin()
- tx.Table("t_test_user").Where("id = ?", 4).Update("name", "77")
- tx.Table("t_test_user").Where("id = ?", 5).Update("name", "88")
- tx.SavePoint("test-point")
- tx.Table("t_test_user").Where("id = ?", 6).Update("name", "99")
- tx.RollbackTo("test-point")
- // 提交事务
- tx.Commit()
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。