-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
57 lines (47 loc) · 1.18 KB
/
main.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
package main
import (
"dingding/controller/user"
"dingding/middlewares"
"dingding/server"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type Product struct {
gorm.Model
Title string
Code string
Price uint
}
func main() {
server.
Init().
SetMiddlewares(
middlewares.Cors(),
).
Route(
user.Controllers(),
).
Listen()
}
func DbTest() {
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
// Migrate the schema
db.AutoMigrate(&Product{})
// 插入内容
db.Create(&Product{Title: "新款手机", Code: "D42", Price: 1000})
db.Create(&Product{Title: "新款电脑", Code: "D43", Price: 3500})
// 读取内容
var product Product
db.First(&product, 1) // find product with integer primary key
db.First(&product, "code = ?", "D42") // find product with code D42
// 更新操作:更新单个字段
db.Model(&product).Update("Price", 2000)
// 更新操作:更新多个字段
db.Model(&product).Updates(Product{Price: 2000, Code: "F42"}) // non-zero fields
db.Model(&product).Updates(map[string]interface{}{"Price": 2000, "Code": "F42"})
// 删除操作:
db.Delete(&product, 1)
}