beego--orm实例

5 篇文章 0 订阅
控制器: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))
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值