首先关于数据库的配置,放行conf/app.conf里,如下:
~~~
dbuser = root
dbpassword = root
dbname = test
dbcharset = utf8
~~~
然后在models/目录新建个模型models.go
~~~
package models
import (
"github.com/astaxie/beego/orm"
)
type Article struct {
Id int `orm="auto;pk"`
Author string `orm="size(16)"`
Title string `orm="size(64)"`
Content string
Create_time int64
}
func Init() {
orm.RegisterModel(new(Article))
}
~~~
最后在main.go里导入模型,处理增删除改增
> models.Init() 注册模型
beego.AppConfig.String(key) 获取配置项
~~~
package main
import (
"beego_blog/models"
_ "beego_blog/routers"
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
"time"
)
func init() {
dbuser := beego.AppConfig.String("dbuser")
dbpassword := beego.AppConfig.String("dbpassword")
dbname := beego.AppConfig.String("dbname")
dbcharset := beego.AppConfig.String("dbcharset")
orm.Debug = true
models.Init()
orm.RegisterDriver("mysql", orm.DRMySQL)
orm.RegisterDataBase("default", "mysql", dbuser+":"+dbpassword+"@/"+dbname+"?charset="+dbcharset)
}
func main() {
o := orm.NewOrm()
o.Using("default")
// 增加
article := models.Article{}
article.Title = "hello go"
article.Author = "zhangsan"
article.Content = "hello bee go"
article.Create_time = time.Now().Unix()
id, err := o.Insert(&article)
if err == nil {
fmt.Println(id)
}
// 删除
// 查询
// 更新
beego.Run()
}
~~~
删除( 根据Id )
~~~
if num, err := o.Delete(&models.Article{Id: 7}); err == nil {
fmt.Println("删除影响的行数:")
fmt.Println(num)
} else {
fmt.Println("删除失败~")
}
~~~
查询( 根据Id )
~~~
article := models.Article{Id: 8}
err := o.Read(&article)
if err == orm.ErrNoRows {
fmt.Println("查询不到")
} else if err == orm.ErrMissPK {
fmt.Println("找不到主键")
} else {
fmt.Println(article.Id, article.Author)
}
~~~
更新( 根据Id )
~~~
article := models.Article{Id: 8}
if o.Read(&article) == nil {
article.Author = "lisi"
if num, err := o.Update(&article); err == nil {
fmt.Println(num)
} else {
fmt.Println("更新失败~")
}
}
~~~