beego框架中orm的使用
//package main
//
//import (
// _ "myproject/routers"
// "github.com/astaxie/beego"
// "github.com/astaxie/beego/orm"
// "fmt"
//)
//
//func main() {
// //beego.SetStaticPath("/down1","download1") ,自定義設定多個靜態檔案處理目錄
// beego.Run()
//}
// 上面是入門的案例, 下面是beego框架中orm的使用
package main
import (
_ "myproject/routers"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"fmt"
)
type User struct{
Id int
Name string `orm:"size(100)"`
}
type Post struct{
Id int `orm:"auto"`
Title string `orm:"size(100)"`
User *User `orm:"rel(fk)"`
}
func init(){
// set default dabase
orm.RegisterDataBase("default","mysql", "root:[email protected]
//register model
orm.RegisterModel(new(User))
//建立table
orm.RunSyncdb("default", false, true)
}
func main() {
//beego.SetStaticPath("/down1","download1") ,自定義設定多個靜態檔案處理目錄
// 五,除錯查詢日誌
//開發環境中,輸出日誌
// [ORM] - 2013-08-09 13:18:16 - [Queries/default] - [ db.Exec / 0.4ms] - [INSERT INTO `user` (`name`) VALUES (?)] - `slene`
orm.Debug = true
o := orm.NewOrm()
user := User{Name:"slence"}
//一,通過orm進行增刪改查
//insert
id, err := o.Insert(&user)
fmt.Printf("ID:%d, ERR: %v\n", id, err)
//update
user.Name = "astaxie"
num, err := o.Update(&user)
fmt.Printf("NUM:%d, ERR:%v\n", num, err)
//read one
u := User{Id:user.Id}
err = o.Read(&u)
fmt.Printf("ERR:%v\n", err)
//delete
num, err = o.Delete(&u)
fmt.Printf("NUM:%d, ERR:%v\n", num, err)
// 二,關聯查詢,主要還是在於Post的結構體中User欄位定義了外來鍵關聯
var posts []*Post
qs := o.QueryTable("post")
num, err = qs.Filter("User_name", "slence").All(&posts)//不用:=是因為上面意見有num了,此處僅僅是修改
fmt.Printf("NUM:%d, ERR:%v\n", num, err)
// 三,使用原生的SQL語句進行查詢
var maps []orm.Params
num, err= o.Raw("SELECT * FROM user").Values(&maps)
fmt.Printf("NUM:%d, ERR:%v\n", num, err)
for _, term := range maps{
fmt.Println(term["id"], ":", term["name"])
}
//四,事務的處理
//o.Begin
//。。。。
//o := NewOrm()
//user := User{Name:"slence"}
//id, err := o.Insert(&user)
//if err == nil{
// o.Commit()
//}else{
// o.Rollback()
//}
beego.Run()
}