周威學Go從入門到放棄第十四篇(beego框架入門篇)
阿新 • • 發佈:2018-12-31
下載框架包(本人mac)
go get github.com/astaxie/beego
package main import ( "errors" "fmt" "github.com/astaxie/beego/orm" _ "github.com/go-sql-driver/mysql" // 匯入資料庫驅動 ) type People struct { Id int64 Username string `orm:"size(100)"` } func init() { orm.RegisterDataBase("default", "mysql", "root:[email protected]
(localhost:3306)/test?charset=utf8", 30) // 註冊定義的 entity orm.RegisterModel(new(People)) // 建立 table // name means table's alias name. default is "default". // force means run next sql if the current is error. // verbose means show all info when running command or not. orm.RunSyncdb("default", false, true) } func main() { o := orm.NewOrm() fmt.Println("--------插入使用者-------") insertPeople(o) fmt.Println("--------查詢使用者-------") user, err := getPeople(o, 1) checkError(err) fmt.Println(user) fmt.Println("--------更新使用者-------") udpatePeople(o, 1) fmt.Println("--------查詢使用者-------") user, err = getPeople(o, 1) checkError(err) fmt.Println(user) fmt.Println("--------刪除使用者-------") deletePeople(o, 3) } func getPeople(o orm.Ormer, id int64) (People, error) { user := People{Id: id} err := o.Read(&user) if err == orm.ErrNoRows || err == orm.ErrMissPK { fmt.Println("no rows") return user, errors.New("no rows") } else { return user, nil } } func udpatePeople(o orm.Ormer, id int64) { user, err := getPeople(o, id) checkError(err) user.Username = "Hello World" res, err := o.Update(&user) checkError(err) fmt.Println("影響的行數", res) } func deletePeople(o orm.Ormer, id int64) { people := People{Id: id} affect, err := o.Delete(&people) checkError(err) fmt.Println("deleted nums:", affect) } func insertPeople(o orm.Ormer) { user := People{Username: "golang"} // 插入表 id, err := o.Insert(&user) checkError(err) fmt.Println("lastInsertId:", id) } func checkError(err error) { if err != nil { panic(err) } }