han-joker 2 years ago
parent 7165f7f2e5
commit 3a354c2134

@ -40,21 +40,6 @@ func BasicUsage() {
fmt.Println("migrate success")
}
var DB *gorm.DB
func init() {
// 定义DSN
const dsn = "root:secret@tcp(127.0.0.1:3306)/gormExample?charset=utf8mb4&parseTime=True&loc=Local"
// 连接服务器(池)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal(err)
}
DB = db
}
func Create() {
// 构建Article类型数据
article := &Article{
@ -123,3 +108,25 @@ func Delete() {
// print
fmt.Println("article was deleted")
}
func Debug() {
// insert
article := &Article{
Subject: "GORM 的 CRUD 基础操作",
PublishTime: time.Now(),
}
if err := DB.
Debug().
Create(article).Error; err != nil {
log.Fatal(err)
}
// select
if err := DB.Debug().First(article, article.ID).Error; err != nil {
log.Fatal(err)
}
}
func Log() {
Create()
}

@ -21,3 +21,11 @@ func TestUpdate(t *testing.T) {
func TestDelete(t *testing.T) {
Delete()
}
func TestDebug(t *testing.T) {
Debug()
}
func TestLog(t *testing.T) {
Log()
}

@ -0,0 +1,69 @@
package gormExample
import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
"io"
"log"
"os"
"time"
)
var DB *gorm.DB
// 配置全局日志级别
//func init() {
// // 定义DSN
// const dsn = "root:secret@tcp(127.0.0.1:3306)/gormExample?charset=utf8mb4&parseTime=True&loc=Local"
//
// // 连接服务器(池)
// db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
// // 设置Info级别的默认日志
// Logger: logger.Default.LogMode(logger.Info),
// })
// if err != nil {
// log.Fatal(err)
// }
//
// DB = db
//}
// 自定义日志
var logWriter io.Writer
func init() {
// 定义DSN
const dsn = "root:secret@tcp(127.0.0.1:3306)/gormExample?charset=utf8mb4&parseTime=True&loc=Local"
// 初始化logWriter
logWriter, _ = os.OpenFile("./sql.log", os.O_CREATE|os.O_APPEND, 0644)
customLogger := logger.New(log.New(logWriter, "\n", log.LstdFlags),
logger.Config{
// 慢查询阈值 200ms
SlowThreshold: 200 * time.Millisecond,
// 日志级别
LogLevel: logger.Info,
// 是否忽略记录不存在的错误
IgnoreRecordNotFoundError: false,
// 不彩色化
Colorful: false,
})
// 连接服务器(池)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
// 设置为自定义的日志
Logger: customLogger,
// 设置默认的命名策略的选项
NamingStrategy: schema.NamingStrategy{
TablePrefix: "msb_",
SingularTable: true,
NameReplacer: nil,
NoLowerCase: false,
},
})
if err != nil {
log.Fatal(err)
}
DB = db
}

@ -0,0 +1,54 @@
package gormExample
import (
"fmt"
"gorm.io/gorm"
"log"
"time"
)
type Post struct{ gorm.Model }
type Category struct{ gorm.Model }
type PostCategory struct{ gorm.Model }
type Box struct{ gorm.Model }
func (Box) TableName() string {
return "my_box"
}
type TypeMap struct {
gorm.Model
FInt int
FUInt uint
FFloat32 float32
FFloat64 float64
FString string
FTime time.Time
FByteSlice []byte
FIntP *int
FUIntP *uint
FFloat32P *float32
FFloat64P *float64
FStringP *string
FTimeP *time.Time
}
func Migrate() {
if err := DB.Debug().AutoMigrate(&TypeMap{}, &Post{}, &Category{}, &PostCategory{}, &Box{}); err != nil {
log.Fatal(err)
}
}
func PointerDiff() {
// 模型的零值
typeMap := &TypeMap{}
fmt.Printf("%+v\n", typeMap)
fmt.Println("=================================")
// 查询数据NULL对应的值
DB.First(typeMap, 1)
fmt.Printf("%+v\n", typeMap)
}

@ -0,0 +1,11 @@
package gormExample
import "testing"
func TestMigrate(t *testing.T) {
Migrate()
}
func TestPointerDiff(t *testing.T) {
PointerDiff()
}
Loading…
Cancel
Save