当前位置:网站首页>11-gorm-v2-02-create data
11-gorm-v2-02-create data
2022-07-05 06:15:00 【Operation and maintenance xuandegong】
List of articles
1. A simple example
db.Create(&liuBei)
- Complete example
package main
import (
"database/sql"
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"time"
)
type User struct {
ID int64
Age int64
Name string
}
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
liuBei := User{
Name: "LiuBei",
Age: 28,
}
db.Create(&liuBei)
}
func connect() (db *gorm.DB,sqlDB *sql.DB,err error) {
dsn := "root:[email protected](127.0.0.1:3306)/crow?charset=utf8&parseTime=True&loc=Local"
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
})
sqlDB,_ = db.DB()
if err != nil {
fmt.Printf(err.Error())
defer sqlDB.Close()
}else {
fmt.Printf("OK\n")
sqlDB.SetMaxIdleConns(10)
sqlDB.SetMaxOpenConns(100)
sqlDB.SetConnMaxLifetime(time.Hour)
}
return
}
2. Create a record with the specified field
- Use the specified field
db.Select("name").Create(&liuBei)
- Exclude the specified fields
db.Omit("name").Create(&liuBei)
3. Batch insert
3.1 Create with array slices
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
var users = []User{
{
Name: "LiuBei",Age: 28}, {
Name: "GuanYu",Age: 22}, {
Name: "ZhangFei",Age: 20}}
db.Create(&users)
fmt.Println(users)
}
- Output
OK
[{
8 28 LiuBei} {
9 22 GuanYu} {
10 20 ZhangFei}]
- Database table results
mysql> select * from users;
+----+------+----------+
| id | age | name |
+----+------+----------+
| 8 | 28 | LiuBei |
| 9 | 22 | GuanYu |
| 10 | 20 | ZhangFei |
+----+------+----------+
3 rows in set (0.00 sec)
3.2 CreateInBatches Batch creation
The test was not successful , Will still create 5 Data .
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
//db.Migrator().CreateTable(&User{})
user := []User{
{
Name: "soldier_01"},{
Name: "soldier_02"},{
Name: "soldier_03"},{
Name: "soldier_04"},{
Name: "soldier_05"}}
db.CreateInBatches(user, 3)
}
4. Create hook
4.1 Concept
GORM Allow user-defined hooks
BeforeSave,BeforeCreate,AfterSave,AfterCreateestablish
func (u *User) BeforeCreate(tx *gorm.DB) (err error) {
u.Name = "Shi_Bing"
return
}
4.2 Complete example
- Code
In the example, a table is created by slicing , Ought to be
soldier_01Tosoldier_05. But becauseBeforeCreateThe existence of methods , In the actual tablenameAll of themshi_bing
package main
import (
"database/sql"
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"time"
)
type User struct {
ID int64
Age int64
Name string
}
func (u *User) BeforeCreate(tx *gorm.DB) (err error) {
u.Name = "Shi_Bing"
return
}
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
user := []User{
{
Name: "soldier_01"},{
Name: "soldier_02"},{
Name: "soldier_03"},{
Name: "soldier_04"},{
Name: "soldier_05"}}
db.Create(&user)
fmt.Println(user)
}
func connect() (db *gorm.DB,sqlDB *sql.DB,err error) {
dsn := "root:[email protected](127.0.0.1:3306)/crow?charset=utf8&parseTime=True&loc=Local"
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
})
sqlDB,_ = db.DB()
if err != nil {
fmt.Printf(err.Error())
defer sqlDB.Close()
}else {
fmt.Printf("OK\n")
sqlDB.SetMaxIdleConns(10)
sqlDB.SetMaxOpenConns(100)
sqlDB.SetConnMaxLifetime(time.Hour)
}
return
}
- Output
OK
[{
16 0 Shi_Bing} {
17 0 Shi_Bing} {
18 0 Shi_Bing} {
19 0 Shi_Bing} {
20 0 Shi_Bing}]
- Database table
mysql> select * from users;
+----+------+----------+
| id | age | name |
+----+------+----------+
| 16 | 0 | Shi_Bing |
| 17 | 0 | Shi_Bing |
| 18 | 0 | Shi_Bing |
| 19 | 0 | Shi_Bing |
| 20 | 0 | Shi_Bing |
+----+------+----------+
5 rows in set (0.00 sec)
4.3 Skip hook
SkipHooks Session mode can skip hooks .
db.Session(&gorm.Session{
SkipHooks: true}).Create(&user)
5. according to MAP establish
user := map[string]interface{
}{
"Name":"GuanYu",
"Age":22,
}
db.Model(&User{
}).Create(user)
边栏推荐
- Leetcode divide and conquer / dichotomy
- 剑指 Offer II 058:日程表
- Daily question 1984 Minimum difference in student scores
- Daily question 1342 Number of operations to change the number to 0
- Liunx starts redis
- Flutter Web 硬件键盘监听
- 4. 对象映射 - Mapping.Mapster
- LeetCode 0108.将有序数组转换为二叉搜索树 - 数组中值为根,中值左右分别为左右子树
- Daily question 1688 Number of matches in the competition
- [rust notes] 17 concurrent (Part 2)
猜你喜欢

Appium foundation - use the first demo of appium

LeetCode 0107.二叉树的层序遍历II - 另一种方法

Groupbykey() and reducebykey() and combinebykey() in spark

Leetcode-6108: decrypt messages

SQLMAP使用教程(一)

Some common problems in the assessment of network engineers: WLAN, BGP, switch

SQLMAP使用教程(二)实战技巧一

Redis publish subscribe command line implementation

LVS简介【暂未完成(半成品)】

Sqlmap tutorial (1)
随机推荐
leetcode-1200:最小绝对差
Sqlmap tutorial (II) practical skills I
The sum of the unique elements of the daily question
2022年貴州省職業院校技能大賽中職組網絡安全賽項規程
MIT-6874-Deep Learning in the Life Sciences Week 7
MySQL advanced part 2: storage engine
[rust notes] 14 set (Part 2)
Flutter Web 硬件键盘监听
Leetcode-6110: number of incremental paths in the grid graph
1.14 - 流水线
Leetcode recursion
【Rust 笔记】15-字符串与文本(下)
【Rust 笔记】16-输入与输出(下)
MySQL advanced part 1: triggers
Daily question 1189 Maximum number of "balloons"
leetcode-3:无重复字符的最长子串
【LeetCode】Day95-有效的数独&矩阵置零
[rust notes] 14 set (Part 1)
Leetcode dynamic programming
1.13 - RISC/CISC