Go語言之高級篇beego框架之controller調用model

1、controller調用modelmysql

開發規範,就該把對數據庫的操做寫在model文件夾中。git

示例:github

views/main.goweb

package main

import (
	_ "web/routers"
	"github.com/astaxie/beego"
)

func main() {
	beego.Run()
}

routers/router.gosql

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中調用modelstcp

controllers/testModel.gopost

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!

查看數據庫中是否插入成功。orm

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)
相關文章
相關標籤/搜索