使用orm可以款速的建表等操作
下载包文件
go get github.com/go-xorm/xorm
创建全局orm句柄
import (
"Gin_demo/CloudRestaurant/model"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/go-xorm/xorm"
)
//全局orm句柄 OrmEngine方法中赋值 OrmEngine在main方法中初始化
var DbEngine * Orm
type Orm struct {
*xorm.Engine
}
func OrmEngine(cfg * Config) (*Orm, error) {
database := cfg.Database
//连接数据库
conn := database.User+":"+database.Password+"@tcp("+database.Host+":"+database.Port+")/"+database.DbName+"?charset="+database.Chartset
engine, err := xorm.NewEngine("mysql",conn)
if err!=nil {
return nil, err
}
fmt.Println("[数据库连接成功]:",conn)
engine.ShowSQL(database.ShowSql)
//自动创建表, 如果表已经存在, 则不创建
err = engine.Sync2(new(model.SmsCode))
if err!=nil {
return nil, err
}
fmt.Println("[创建表成功:SmsCode]")
err = engine.Sync2(new(model.Member))
if err!=nil {
return nil, err
}
fmt.Println("[创建表成功:Member]")
err = engine.Sync2(new(model.FoodCategory))
if err!=nil {
return nil, err
}
fmt.Println("[创建表成功:FoodCategory]")
orm := Orm{engine}
DbEngine = &orm
return &orm, nil
}