控制器:sql.go
package controllers
import (
"BLOG/models"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
)
func init() {
//注册驱动
orm.RegisterDriver("mysql", orm.DRMySQL)
//注册连接(默认数据库)
orm.RegisterDataBase("default", "mysql", "root:******@/gosql?charset=utf8")
//其他数据库
orm.RegisterDataBase("db1", "mysql", "root:******@/gotest?charset=utf8")
}
type TestController struct {
BaseController
}
// @router /test [get]
func (c *TestController) Test() {
//使用默认数据库
o := orm.NewOrm()
stu := new(models.Student) //new()创建变量
stu.No="001"
stu.Score="98"
o.Insert(stu)
//切换数据库
o1 :=orm.NewOrm()
o1.Using("db1")
info := new(models.Info)
info.Name="zhangsan"
info.Age="20"
o1.Insert(info)
c.Ctx.WriteString("end")
}
model层:models.go
package models
import (
"github.com/astaxie/beego/orm"
)
type Student struct {
Id int
No string
Score string
}
type Info struct {
Id int
Name string
Age string
}
func init() {
// 需要在init中注册定义的model
orm.RegisterModel(new(Info),new(Student))
}