beego增删改查
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) }
package controllers import ( "encoding/json" "fmt" "github.com/astaxie/beego" "github.com/astaxie/beego/orm" _ "github.com/go-sql-driver/mysql" // import your used driver "strconv" ) var ( o orm.Ormer err error ) func init() { // set default database orm.RegisterDataBase("default", "mysql", "root:root@tcp(192.168.40.10:3306)/wang?charset=utf8", 30) // register model orm.RegisterModel(new(User)) // create table orm.RunSyncdb("default", false, true) o = orm.NewOrm() } type UserController struct { beego.Controller } type User struct { Id int Name string `form:"name"` Age int `form:"age"` Sex string `form:"sex" orm:"size(100)"` } func (this *UserController) UserList() { var users []User num, err := o.QueryTable("user").All(&users) fmt.Printf("Returned Rows Num: %s, %s", num, err) this.Data["json"] = users this.ServeJSON() } func (this *UserController) AddUser() { user := User{} if err := this.ParseForm(&user); err != nil { fmt.Println(err) } id, err := o.Insert(&user) fmt.Printf("ID: %d, ERR: %v\n", id, err) this.Ctx.WriteString("用户新增成功# "+strconv.Itoa(int(id))) } func (this *UserController) EditUser() { var err error user := User{} if err = json.Unmarshal(this.Ctx.Input.RequestBody, &user); err == nil { this.Data["json"] = user } else { this.Data["json"] = err.Error() } this.ServeJSON() } func (this *UserController) DeleteUser() { id := this.GetString(":id") this.Ctx.WriteString("删除用户#" + id) } func (this *UserController) GetUserInfo() { id := this.GetString(":id") i, _ := strconv.Atoi(id) // read one //user := User{Id: i} //err = o.Read(&user) //fmt.Printf("ERR: %v\n", err) var user User err := o.Raw("SELECT * FROM user WHERE id = ?", i).QueryRow(&user) if err != nil { fmt.Println(err) } this.Data["json"] = user this.ServeJSON() }
https://beego.me/docs/mvc/model/overview.md
https://beego.me/docs/mvc/model/rawsql.md