beego ORM是一個強大的Go語言ORM框架。她的靈感主要來自Django ORM和SQLAlchemy。mysql
已經支持的數據庫驅動:git
ORM的特性:github
安裝ORM:sql
go get github.com/astaxie/beego/orm
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 Name string `orm:"size(100)"` } func init() { // set default database orm.RegisterDataBase("default", "mysql", "username:password@tcp(127.0.0.1:3306)/db_name?charset=utf8", 30) // register model orm.RegisterModel(new(User)) // create table orm.RunSyncdb("default", false, true) } func main() { o := orm.NewOrm() user := User{Name: "slene"} // 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) }
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)
當你沒法使用ORM來達到您的需求的時候,也能夠直接使用SQL來完成查詢/映射操做。數據庫
var maps []orm.Params num, err := o.Raw("SELECT * FROM user").Values(&maps) for _,term := range maps{ fmt.Println(term["id"],":",term["name"]) }
事務處理框架
o.Begin() ... user := User{Name: "slene"} id, err := o.Insert(&user) if err == nil { o.Commit() } else { o.Rollback() }
在開發環境下,您可使用如下指令來開啓調試模式:tcp
orm.Debug = true
開啓後將會輸出全部的查詢語句,包括執行、準備、事務等。例如post
[ORM] - 2013-08-09 13:18:16 - [Queries/default] - [ db.Exec / 0.4ms] - [INSERT INTO `user` (`name`) VALUES (?)] - `slene`