当前位置:网站首页>11-gorm-v2-02-create data

11-gorm-v2-02-create data

2022-07-05 06:15:00 Operation and maintenance xuandegong

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, AfterCreate

  • establish

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_01 To soldier_05. But because BeforeCreate The existence of methods , In the actual table name All of them shi_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)	
原网站

版权声明
本文为[Operation and maintenance xuandegong]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140619059059.html