golang之gorm简单实战

使用golang中的gorm库来操作数据库
gorm提供了非常友好的api来操作数据库
直接操作go中的struct实体就可以操作数据表
非常简单,方便,易用。

这里示例数据库使用的是sqlite3
当前也可以使用mysql,PostgreSQL数据库。

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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
package main

import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"fmt"
)


/**
type Model struct {
ID uint `gorm:"primary_key"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time `sql:"index"`
}
*/

// 定义一个表 products
type Product struct {
gorm.Model // 这里默认会再添加四个字段,看上面源码,该结构体model中包含ID, CreateAt, UpdateAt, DeleteAt四个字段值
Code string
Price uint
Name string `gorm:"type:varchar(100);not null;column:product_name"`
FirstName string // 这里会自动将数据中该字段转换成 first_name
}

/**

sqlite3 test.db
.headers on
.mode column
.table

select * from products

// 查看表结构
select * from sqlite_master where type = "table";

sqlite> select * from products;
id created_at updated_at deleted_at code price
---------- -------------------------------- ------------------------------- ---------- ---------- ----------
1 2019-05-12 19:02:28.105122+08:00 2019-05-12 19:02:44.54523+08:00 L1212 2000
2 2019-05-12 19:02:44.54346+08:00 2019-05-12 19:02:44.54346+08:00 L1212 1000
*/

var Sqlite *gorm.DB

func init() {
// test.db本质是一个文件夹, 会出现在当前目录下
db, err := gorm.Open("sqlite3", "test.db")
if err != nil {
panic("连接数据库失败")
}
Sqlite = db
}

func main() {

// 自动迁移模式, 创建数据表
Sqlite.AutoMigrate(&Product{})

// 创建
// db.Create(&Product{Code: "L1212", Price: 1000})

// 读取
// var product Product
// db.First(&product, 1) // 查询id为1的product
// db.First(&product, "code = ?", "L1212") // 查询code为l1212的product

// // 更新 - 更新product的price为2000
// db.Model(&product).Update("Price", 2000)

// 删除 - 删除product
// db.Delete(&product)

// CreateDBData()
FindById(2)
FindByLikeName("d")

UpdateNameById("dottie", 1)

DeleteById(5)

defer Sqlite.Close()
}

// 根据id删除
func DeleteById(id uint) {
var product Product
if dbError := Sqlite.First(&product, id).Error; dbError != nil {
fmt.Println(dbError.Error())
return
}

fmt.Println("开始删除", product.ID, product.Name)

if dbError := Sqlite.Delete(&product).Error; dbError != nil {
fmt.Println(dbError.Error())
return
}
// 删除成功后。其实就是将gorm.Model.DeleteAt字段值设置未删除的日期。记录还在的
/**
id created_at updated_at deleted_at code price product_name first_name
---------- -------------------------------- -------------------------------- ---------- ----------- ---------- ------------ ----------
4 2019-05-12 19:26:21.845485+08:00 2019-05-12 19:26:21.845485+08:00 code-hangzh 3 hangzhou
5 2019-05-12 19:26:21.846248+08:00 2019-05-12 19:26:21.846248+08:00 2019-05-12 code-nancai 4 nancai
*/
fmt.Println("删除成功")
}

// 根据id更新ProductName
func UpdateNameById(name string, id int) {
var product Product

if dbError := Sqlite.First(&product, "id = ?", id).Error; dbError != nil {
fmt.Println(dbError.Error())
return
}

fmt.Println("old = ", product)

if dbError := Sqlite.Model(&product).Update("Name", name).Error; dbError != nil {
fmt.Println(dbError.Error())
return
}
fmt.Println("new = ", product)
}

// 模糊查询 ProductName
func FindByLikeName(name string) {
var products []Product
// 这里Where里面的字段可以是数据库中的字段名称,也可以是ORM也就是struct中的ProductName名称。
if dbError := Sqlite.Where("product_name LIKE ?", name+"%").Find(&products).Error; dbError != nil {
fmt.Println(dbError.Error())
return
}
fmt.Println(products)
}

// 根据id查找
func FindById(id int) {
var product Product
if dbError := Sqlite.Where("id = ?", id).First(&product).Error; dbError != nil {
fmt.Println(dbError.Error())
return
}
fmt.Println(product, product.Name)
}

// 插入5条数据
func CreateDBData() {
// 插入五条数据
var nameList = []string{"dottie", "daejong", "china", "hangzhou", "nancai"}
for index, name := range nameList {
var product Product
product = Product{
Code: "code-" + name,
Price: uint(index),
Name: name,
}
Sqlite.Create(&product)
}
}