周威学Go从入门到放弃第十四篇(beego框架入门篇)

下载框架包(本人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:root@tcp(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)
	}
}

 

你可能感兴趣的:(Go,GO语言学习,beego,go,框架,orm,lang)