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 }
// 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()
一个具体的例子
funcCreateAnimals(db *gorm.DB)error { // Note the use of tx as the database handle once you are within a transaction tx := db.Begin() deferfunc() { if r := recover(); r != nil { tx.Rollback() } }()