单独使用beego中的orm

2014-12-03 19:22 来源:www.chinab4c.com 作者:golang专家

  单独使用beego中的orm使用,脱离beego单独项目中使用.

  1:models/base.go

   package models
import (
    "github.com/astaxie/beego/orm"
    _ "github.com/go-sql-driver/mysql"
    "fmt"
)

func Init() {
    dburl := "root:"+ "@tcp(localhost:3306)/274utftest?charset=utf8"
    orm.RegisterDataBase("default", "mysql", dburl, 30)
    orm.RegisterModel(new(Users))
}

func TableName(tabname string) string {
    fmt.Println(fmt.Sprintf("%s%s","ecs_",tabname))
    return fmt.Sprintf("%s%s","ecs_",tabname)
}
 

2:models/users.go

package models
import (
    "github.com/astaxie/beego/orm"
    _ "github.com/go-sql-driver/mysql"
)

type Users struct {
    User_id   int    `orm:"pk"`
    User_name string `orm:"size(100)"`
}

func (m *Users) TableName() string {
    return TableName("users")
}

func (m *Users) Query() orm.QuerySeter {
    return orm.NewOrm().QueryTable(m)
}

func (m *Users) Read(fields ...string) error {
    if err := orm.NewOrm().Read(m, fields...); err != nil {
        return err
    }
    return nil
}

3:主程序main.go

package main
import (
    "yangsheng/models"
    "fmt"
  
)

func main() {
    models.Init()
    u := models.Users{User_id: 8}
    err :=u.Read("user_id")
    fmt.Println(err)
    fmt.Println(u)
    var mm models.Users
    mm.User_id = 2
    mm.User_name = "ddd"
    tt:=make(map[string]interface{})
    tt["a"] =mm
    tt["x"] = "aa"
    fmt.Println(tt)
}

以上实现了单独使用beego中的orm

来源:http://www.chinab4c.com