背景:
MVC是系統開發常用的框架,Models 模型層用來處理數據 ,本篇使用beego框架,演示 models層的用法
代碼:
在models 路徑下面創建一個go文件 ,用來處理數據庫鏈接,CRUD等相關操作
package models
import (
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
)
var (
db orm.Ormer
)
//UserInfo is defined a struct of user
type UserInfo struct {
ID int64
Username string
Password string
}
// Init connect database
func init() {
orm.Debug = true //打開調試模式
orm.RegisterDataBase("default", "mysql", "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8", 30)
orm.RegisterModel(new(UserInfo))
db = orm.NewOrm()
}
//Adduser to add a user
func Adduser(userinfo *UserInfo) (int64, error) {
id, err := db.Insert(userinfo)
return id, err
}
這裏需要注意 包裏面的init方法 比較特殊 ,函數名字要小寫
再實現一個controller
package controllers
import (
"WEB/models"
"strconv"
"github.com/astaxie/beego"
)
//ModuleController is a Controller to handel struct of models
type ModuleController struct {
beego.Controller
}
//Get is a function
func (c *ModuleController) Get() {
//c.Ctx.WriteString("test moudle")
user := models.UserInfo{Username: "wangwu", Password: "56789"}
id, _ := models.Adduser(&user)
c.Ctx.WriteString(strconv.FormatInt(id, 10))
}
主要操作是
1.創建用戶
2.執行添加用戶操作
運行
bee run
瀏覽器可以查看到輸出的用戶id
http://127.0.0.1:8080/modulecontrol
輸出 3
查看數據庫
wangwu這個用戶已經添加了進來