• beego orm


    http://beego.me/docs/mvc/model/overview.md

    go get github.com/astaxie/beego/orm

    Simple Usage

    package main
    
    import (
        "fmt"
        "github.com/astaxie/beego/orm"
        _ "github.com/go-sql-driver/mysql" // import your used driver
    )
    
    // Model Struct
    type User struct {
        Id   int    `orm:"auto"`
        Name string `orm:"size(100)"`
    }
    
    func init() {
        // register model
        orm.RegisterModel(new(User))
    
        // set default database
        orm.RegisterDataBase("default", "mysql", "root:root@/my_db?charset=utf8", 30)
    }
    
    func main() {
        o := orm.NewOrm()
    
        user := User{Name: "slene"}
    
        // insert
        id, err := o.Insert(&user)
    
        // update
        user.Name = "astaxie"
        num, err := o.Update(&user)
    
        // read one
        u := User{Id: user.Id}
        err = o.Read(&u)
    
        // delete
        num, err = o.Delete(&u) 
    }
    

    Next with relation

    type Post struct {
        Id    int    `orm:"auto"`
        Title string `orm:"size(100)"`
        User  *User  `orm:"rel(fk)"`
    }
    
    var posts []*Post
    qs := o.QueryTable("post")
    num, err := qs.Filter("User__Name", "slene").All(&posts)
    

    Use Raw sql

    If you don't like ORM,use Raw SQL to query / mapping without ORM setting

    var maps []Params
    num, err := o.Raw("SELECT id FROM user WHERE name = ?", "slene").Values(&maps)
    if num > 0 {
        fmt.Println(maps[0]["id"])
    }
    

    Transaction

    o.Begin()
    ...
    user := User{Name: "slene"}
    id, err := o.Insert(&user)
    if err != nil {
        o.Commit()
    } else {
        o.Rollback()
    }
    
    

    Debug Log Queries

    In development env, you can simple use

    func main() {
        orm.Debug = true
    ...
    

    enable log queries.

    output include all queries, such as exec / prepare / transaction.

    like this:

    [ORM] - 2013-08-09 13:18:16 - [Queries/default] - [    db.Exec /     0.4ms] - [INSERT INTO `user` (`name`) VALUES (?)] - `slene`
    ...
    

    note: not recommend use this in product env.

     

  • 相关阅读:
    1.centos install jdk
    SSH命令行上传/下载文件
    关于CXF的FrontEnd和数据绑定方案
    Eclipse反编译工具Jad及插件JadClipse配置
    Eclipse背景颜色修改
    Java IDE-常见Java开发工具的特点比较
    myBatis应用
    [Java EE] LInux环境下Eclipse + Tomcat + MySQL 配置J2EE开发环境的方法
    Eclipse EMT Papyrus建模和MoDisco反向工程
    (转载)C# 正则表达式
  • 原文地址:https://www.cnblogs.com/wangxusummer/p/4062931.html
Copyright © 2020-2023  润新知