beego使用mysql

目标

  • 演示beego 的 orm框架,通过orm调用mysql驱动实现增删改查

新建项目

bee new beego_mysql

修改配置文件

appname = beego_mysql
runmode = dev
httpport = 8080
# 关闭自动渲染
AutoRender = false
copyrequestbody=true

models

在models目录下新建user_model.go,使用orm映射数据库数据,如果数据库中没有这个表会自动新建,有的话忽略。

package models

import (
	"github.com/astaxie/beego/orm" //导入orm框架
	"github.com/beego/beego/v2/core/logs"
	_ "github.com/go-sql-driver/mysql" //导入数据库驱动
	"time"
)

//定义user表模型结构
type TestUser struct {
	Id   int `orm:"pk;auto;column(user_id)"` //表示设置为主键并且自增,列名为user_id
	Name string `orm:"size(100)"column(user_name)`
	Sex  string `orm:"size(20);column(gender)"`
	CreateDate time.Time `orm:"type(date);column(create_date)"`
	Age int `orm:size(10);column(age)`
}
//注意:以上的字段名必须大写,否则无法识别

var mysql_orm orm.Ormer

func init() {
	//注册数据库,一共有五个参数,后面连个用于连接池操作
	_ = orm.RegisterDataBase("default", "mysql",
		"root:123456@tcp(192.168.99.100:3306)/test?charset=utf8")
	//进行注册模型结构,可以有多个,用逗号分隔
	orm.RegisterModel(new(TestUser))
	//创建表,默认为default,只建立一次,后面再执行这个会忽略
	_ = orm.RunSyncdb("default", false, true)
	mysql_orm = orm.NewOrm()
}
//添加用户
func AadUser(user *TestUser)(int64,error){
	id,err:=mysql_orm.Insert(user)
	if err != nil{
		logs.Error("err:%s",err.Error())
		//如果出错就回滚
		mysql_orm.Rollback()
	}
	logs.Info("id:%d",id)
	return id,err
}
//获取所有用户
func ReadAllUser() []orm.Params{
	var maps []orm.Params
	mysql_orm.Raw("select * from test_user").Values(&maps)
	logs.Info("maps %v",maps)
	return maps
}

//根据id删除用户
func Deletebyid(id int) {
	var user TestUser
	_ = mysql_orm.Raw("delete from test_user where user_id = ?", id).QueryRow(&user)
	logs.Debug(user)
}
//根据id更新信息
func Updatebyid(id int,name string) {
	logs.Debug("update by id %d %s",id,name)
	var user TestUser
	_ = mysql_orm.Raw("update test_user set name=? where user_id=?", name, id).QueryRow(&user)
}

controllers

在controllers目录下新建user_controller.go,在controller中调用模型

package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"beego_mysql/models"
	"github.com/tidwall/gjson"
	"time"
)

type UserController struct{
	beego.Controller
}


func  (c *UserController) AddUser() {
	name:=gjson.Get(string(c.Ctx.Input.RequestBody),"name").String()
	sex:=gjson.Get(string(c.Ctx.Input.RequestBody),"sex").String()
	user := models.TestUser{ Name: name, Sex: sex, CreateDate: time.Now(), Age: 28}
	models.AadUser(&user)
}

func  (c *UserController) GetAllUser(){
	c.Data["json"] = models.ReadAllUser()
	c.ServeJSON(false)
}
func  (c *UserController) DeleteUserById(){
	id,_ := c.GetInt("id")
	models.Deletebyid(id)
}
func  (c *UserController) UpdateUserByid(){
	name:=gjson.Get(string(c.Ctx.Input.RequestBody),"name").String()
	id:=gjson.Get(string(c.Ctx.Input.RequestBody),"id").Int()
	models.Updatebyid(int(id),name)
}

routers

修改路由routers/route.go

package routers

import (
	"beego_mysql/controllers"
	beego "github.com/beego/beego/v2/server/web"
)

func init() {
    beego.Router("/", &controllers.MainController{})

    beego.Router("/addUser",&controllers.UserController{},"post:AddUser")
	beego.Router("/getAllUser",&controllers.UserController{},"get:GetAllUser")
	beego.Router("/deleteUserById",&controllers.UserController{},"get:DeleteUserById")
    beego.Router("/updateUserByid",&controllers.UserController{},"post:UpdateUserByid")

}

运行

bee run

添加用户

126

更新用户

127

查询用户

128

删除用户

129

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×