-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbeego-orm.go
50 lines (39 loc) · 971 Bytes
/
beego-orm.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
package main
import (
"fmt"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql" // 导入数据库驱动
)
// Model Struct
type User struct {
Id int
Name string `orm:"size(100)"`
}
func init() {
// 设置默认数据库
orm.RegisterDataBase("default", "mysql", "root:password@/test?charset=utf8", 30)
// 注册定义的 model
orm.RegisterModel(new(User))
//RegisterModel 也可以同时注册多个 model
//orm.RegisterModel(new(User), new(Profile), new(Post))
// 创建 table
orm.RunSyncdb("default", false, true)
}
func main() {
o := orm.NewOrm()
user := User{Name: "slene"}
// 插入表
id, err := o.Insert(&user)
fmt.Printf("ID: %d, ERR: %v\n", id, err)
// 更新表
user.Name = "astaxie"
num, err := o.Update(&user)
fmt.Printf("NUM: %d, ERR: %v\n", num, err)
// 读取 one
u := User{Id: user.Id}
err = o.Read(&u)
fmt.Println(u)
// 删除表
num, err = o.Delete(&u)
fmt.Printf("NUM: %d, ERR: %v\n", num, err)
}