初始化Go学习项目
This commit is contained in:
37
go-gorm-demo/transaction_savepoint.go
Normal file
37
go-gorm-demo/transaction_savepoint.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
//type User struct {
|
||||
// ID uint `gorm:"primaryKey"`
|
||||
// Name string `gorm:"size:100"`
|
||||
// Email string `gorm:"size:100;unique"`
|
||||
//}
|
||||
|
||||
func main() {
|
||||
db, _ := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
|
||||
db.AutoMigrate(&User{})
|
||||
|
||||
db.Transaction(func(tx *gorm.DB) error {
|
||||
tx.Create(&User{Name: "Alice", Email: "alice@example.com"})
|
||||
|
||||
// 创建 SavePoint
|
||||
tx.SavePoint("sp1")
|
||||
tx.Create(&User{Name: "Bob", Email: "bob@example.com"})
|
||||
|
||||
// 回滚到 SavePoint
|
||||
tx.RollbackTo("sp1")
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
// 检查结果
|
||||
var count int64
|
||||
db.Model(&User{}).Count(&count)
|
||||
fmt.Printf("Total users: %d (should be 1, only Alice)\n", count)
|
||||
}
|
||||
Reference in New Issue
Block a user