beego--orm實例

控制器: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:100521@/gosql?charset=utf8")
   //其他數據庫
   orm.RegisterDataBase("db1", "mysql", "root:100521@/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))
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章