beego orm 操作(sqlite)

beego orm 操作(sqlite)

继续对beego的学习,之前对beego的安装和简单的http请求有了一个大致的了解,接下来就是对数据库的一些操作。

首先我们先定义一个models,在文件夹/models下定义models.go,具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package models
import (
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
)
type UserBT struct {
Id int64 `orm:"pk;auto"` //主键,自动增长
Name string
}
func NewUser(name string) (*UserBT, error) {
if name == "" {
beego.Error("user name is emptry")
return nil, fmt.Errorf("user name is emptry")
}
return &UserBT{Name: name}, nil
}
func init() {
orm.RegisterModel(new(UserBT))
}

这里定义了一个struct,里面有两个成员变量,一个是Id,自增长,还有个是名字Name。

好,现在我们得对main.go进行一下改造,需要在初始化的时候去注册db并创建db表,假如已经存在表了,我们需要不重复创建。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
_ "github.com/mattn/go-sqlite3"
_ "quickstart/routers"
)
//自动建表
func createTable() {
name := "default" //数据库别名
force := false //不强制建数据库
verbose := true //打印建表过程
err := orm.RunSyncdb(name, force, verbose) //建表
if err != nil {
beego.Error(err)
}
}
func init() {
orm.RegisterDataBase("default", "sqlite3", "data.db")
createTable()
}
func main() {
beego.Run()
}

这样子我们就创建了一个叫做data.db的sqlite数据库文件。
我们可以先run一下server并查看db是否创建成功,并多次启动server看看db是否是只创建一次,cd到$GOPATH/src/project目录下,运行bee run

我们可以看到这里将创建表的过程进行了打印,然后我们会在$GOPATH/src/project目录下看到一个data.db文件,nice,数据库文件创建好了!

接下来我们需要往db里头插入一些数据,更新一些数据,根据条件查询等操作,就是我们常说的增删查改。
我们先对Routue.go文件先做一下修改:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package routers
import (
"github.com/astaxie/beego"
"quickstart/controllers"
)
func init() {
beego.Router("/", &controllers.MainController{})
beego.Router("/test", &controllers.TestController{})
beego.Router("/test/:id:int", &controllers.TestController{}, "get:GetInfo")
beego.Router("/test/:id:int/:name:string", &controllers.TestController{}, "get:UpdateInfo")
beego.Router("/testmysql", &controllers.TestMySQLController{})
}

为了做个testcase,我们对之前的testcontroller.go文件做一下简单的修改。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package controllers
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"quickstart/models"
"strconv"
)
type TestController struct {
beego.Controller
}
/**
* Get请求
* @param 每次请求对数据库插入一条新的user
* @return {[type]} [description]
*/
func (c *TestController) Get() {
c.Data["json"] = map[string]interface{}{"rc": 1,
"msg": "success",
"data": false,
}
o := orm.NewOrm()
o.Using("default")
// 插入一条User数据而且名字都赋值为barton
user, err := models.NewUser("barton")
if err == nil {
beego.Debug(o.Insert(user))
}
c.ServeJSON()
}
/**
* 获取User数据
* @param id唯一标识符(自增长)
* @return {[type]} [description]
*/
func (c *TestController) GetInfo() {
id := c.Ctx.Input.Param(":id")
beego.Trace("check id = " + id)
o := orm.NewOrm()
user := new(models.UserBT)
user.Id, _ = strconv.ParseInt(id, 10, 64)
err := o.Read(user)
if err != nil {
beego.Error(err)
c.Data["json"] = map[string]interface{}{"rc": 1,
"msg": "false",
"data": "can not find id = " + id + "from table user",
}
} else {
c.Data["json"] = map[string]interface{}{"rc": 1,
"msg": "success",
"data": map[string]interface{}{
"userId": user.Id,
"userName": user.Name,
},
}
}
c.ServeJSON()
}
/**
* 更新User数据
* @param id唯一标识符(自增长),name 想更新的新的名字
* @return {[type]} [description]
*/
func (c *TestController) UpdateInfo() {
id := c.Ctx.Input.Param(":id")
newName := c.Ctx.Input.Param(":name")
beego.Trace("check id = " + id)
beego.Trace("update name = " + newName)
o := orm.NewOrm()
user := new(models.UserBT)
// 对id做int64的类型转换
user.Id, _ = strconv.ParseInt(id, 10, 64)
// 查找Id == id 的数据
err1 := o.Read(user)
// 查找出错并没找到对应的user数据
if err1 != nil {
beego.Error(err1)
c.Data["json"] = map[string]interface{}{"rc": 1,
"msg": "false",
"data": "can not find id = " + id + "from table user",
}
} else {
user.Name = newName
// 对查找的数据user进行name的更新
_, err2 := o.Update(user, "name")
if err2 != nil {
// 更新失败
beego.Error(err2)
c.Data["json"] = map[string]interface{}{"rc": 1,
"msg": "false",
"data": "update name id = " + id + "from table user",
}
} else {
// 更新成功
c.Data["json"] = map[string]interface{}{"rc": 1,
"msg": "true",
"data": map[string]interface{}{
"userId": user.Id,
"userName": user.Name,
},
}
}
}
c.ServeJSON()
}
func (c *TestController) Post() {
account := c.GetString("account")
password := c.GetString("password")
beego.Info(account)
c.Data["json"] = map[string]interface{}{"rc": 1,
"msg": "success",
"data": map[string]interface{}{
"account": account,
"password": password,
},
}
c.ServeJSON()
}

OK,代码的简单改造已经完成,现在让我们来看看效果吧!
请求localhost:8080/test 插入一条数据

看红色线条块,我们插入了一个Id=12的数据
请求localhost:8080/test/12 查询Id=12的数据

没有问题,那么假设查询的是个Id=999,就是db中木有的数据会发生什么呢?我们测试下,请求localhost:8080/test/999

我们从这可以看到err被捕获并通过相应的处理json进行了返回。

我们试试更新,请求localhost:8080/test/12/tang 更新Id=12的数据将name重新赋值为tang,并将重新获取Id=12的数据将数据用json返回

我们看到更新成功了~!
下面是完整的工程地址:
https://github.com/bartontang/beego_orm_test