Go语言之高级篇beego框架之controller调用model
一、controller调用model
开发规范,就该把对数据库的操作写在model文件夹中。
示例:
views/main.go
package main import ( _ "web/routers" "github.com/astaxie/beego" ) func main() { beego.Run() }
routers/router.go
package routers import ( "web/controllers" "github.com/astaxie/beego" ) func init() { beego.Router("/", &controllers.MainController{}) beego.Router("/test_model", &controllers.TestModelController{}, "get:Get;post:Post") }
models/user.go
package models import ( "github.com/astaxie/beego/orm" _ "github.com/go-sql-driver/mysql" ) //由于model这个名字叫 UserInfo 那么操作的表其实 user_info type UserInfo struct { Id int64 Username string Password string } func init() { orm.Debug = true // 是否开启调试模式 调试模式下会打印出sql语句 orm.RegisterDataBase("default", "mysql", "root:qwe!23@tcp(127.0.0.1:3306)/test?charset=utf8", 30) orm.RegisterModel(new(UserInfo)) } func AddUser(user_info *UserInfo) (int64, error) { o := orm.NewOrm() id, err := o.Insert(user_info) return id, err }
在controllers中调用models
controllers/testModel.go
package controllers import ( "web/models" "github.com/astaxie/beego" ) type TestModelController struct { beego.Controller } func (c *TestModelController) Get() { user := models.UserInfo{Username: "jojo", Password: "123456"} models.AddUser(&user) c.Ctx.WriteString("call model success!") }
执行结果:
http://127.0.0.1:8080/test_model 返回结果: call model success!
查看数据库中是否插入成功。
mysql> select * from user_info; +----+----------+----------+ | id | username | password | +----+----------+----------+ | 1 | nulige | 123456 | | 2 | jojo | 123456 | +----+----------+----------+ 2 rows in set (0.00 sec)
示例2:全局连接实例
models/user.go
package models import ( "github.com/astaxie/beego/orm" _ "github.com/go-sql-driver/mysql" ) //全局连接实例 var ( db orm.Ormer ) //由于model这个名字叫 UserInfo 那么操作的表其实 user_info type UserInfo struct { Id int64 Username string Password string } //实例 func init() { orm.Debug = true // 是否开启调试模式 调试模式下会打印出sql语句 orm.RegisterDataBase("default", "mysql", "root:qwe!23@tcp(127.0.0.1:3306)/test?charset=utf8", 30) orm.RegisterModel(new(UserInfo)) db = orm.NewOrm() } //方法 func AddUser(user_info *UserInfo) (int64, error) { id, err := db.Insert(user_info) return id, err }
controllers/testModel.go
package controllers import ( "web/models" "github.com/astaxie/beego" ) type TestModelController struct { beego.Controller } func (c *TestModelController) Get() { user := models.UserInfo{Username: "limei", Password: "123456"} models.AddUser(&user) c.Ctx.WriteString("call model success!") }
#执行结果:
http://127.0.0.1:8080/test_model call model success!
检查数据库是否插入成功
mysql> select * from user_info; +----+----------+----------+ | id | username | password | +----+----------+----------+ | 1 | nulige | 123456 | | 2 | jojo | 123456 | | 3 | limei | 123456 | +----+----------+----------+ 3 rows in set (0.00 sec)