支援Go所有的類型儲存,且可以用原生SQL敘述與跨資料庫查詢。
go get github.com/astaxie/beego/orm
go get github.com/go-sql-driver/mysql
orm.RegisterDataBase("default", "mysql", "root:root@/xxx?charset=utf8")
orm.SetMaxIdleConns("default", 10)
orm.SetMaxOpenConns("default", 100)
SetMaxIdleConns:閒置時最大連接數。
SetMaxOpenConns:最大連接數。
type BeegoUser struct {
Id int
Name string
Phone string
}
orm.RegisterModel(new(BeegoUser))
orm.RegisterModelWithPrefix("xxx", new(BeegoUser))
o := orm.NewOrm()
o.Using("xxx")
user := new(BeegoUser)
user.Name = "xxx"
user.Phone = "0987654321"
fmt.Println(o.Insert(user))
user := BeegoUser{}
user.Id = 6
// sql: select * from beego_user where id = 6
err := o.Read(&user)
if err == orm.ErrNoRows {
fmt.Println("none")
} else if err == orm.ErrMissPK {
fmt.Println("no key")
} else {
fmt.Println(user.Id, user.Name)
}
user := BeegoUser{}
user.Id = 6
user.Name = "James"
num, err := o.Update(&user)
if err != nil {
fmt.Println("error")
} else {
fmt.Println("更新資料影響的行數:", num)
}
user := BeegoUser{}
user.Id = 7
if num, err := o.Delete(&user); err != nil {
fmt.Println("error")
} else {
fmt.Println("刪除資料影響的行數:", num)
}
o := orm.NewOrm()
var r orm.RawSeter
r = o.Raw("UPDATE user SET name = ? WHERE name = ?", "jack", "tom")
o.Begin()
user1 := BeegoUser{}
user1.Id = 6
user1.Name = "James"
user2 := BeegoUser{}
user2.Id = 12
user2.Name = "Wade"
_, err1 := o.Update(&user1)
_, err2 := o.Insert(&user2)
if err1 != nil || err2 != nil {
o.Rollback()
} else {
o.Commit()
}