CURD基础操作
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
type User struct {
gorm.Model
Name string
Age int
}
func main() {
//打开数据库连接
var db, _ = gorm.Open("sqlite3", "demo.db")
//关闭数据库连接
defer db.Close()
//添加数据库表名前缀
gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
return "demo_" + defaultTableName
}
//创建表
db.AutoMigrate(&User{})
user := User{
Name: "demo",
Age: 20,
}
//插入数据
db.Create(&user)
//查询数据
db.First(&user, "name = ?", "demo")
println(fmt.Sprintf("%v", user))
//更新数据
user.Age = 21
db.Save(&user)
//查询数据
db.First(&user, "name = ?", "demo")
println(fmt.Sprintf("%v", user))
//删除数据,软删除(存在deleted_at字段自动软删除,给deleted_at字段赋值就标记为删除)
db.Delete(&user)
//物理删除
db.Unscoped().Delete(&user)
var count = 0
//查询总数
db.Model(&User{}).Count(&count)
println("user count: ", count)
println("OK")
}