当前位置:网站首页>Gorm data insertion (transfer)

Gorm data insertion (transfer)

2022-07-04 14:10:00 Lucky little yellow man

from :gorm Data insertion

1. Full field attribute insertion

Creat Structure full field attribute insertion

package main

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

// Model structure 
type Student struct {
	Id   int
	Name string
	Age  int
}

func main() {
	// Use dsn Connect to database ,grom Built in database pool 
	// account number : password @ How to connect (ip Address : Port number )/ database ? The way of language , The time zone ( If the time zone is not set 8 The hour system )
	dsn := "root:[email protected](127.0.0.1:3306)/gotest?charset=utf8mb4&parseTime=True&loc=Local"
	conn, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) // Use mysq Connect to database , The second parameter can add more configurations ( not essential )
	if err != nil {
		fmt.Println(err)
	}
	conn.AutoMigrate(&Student{}) // Create table ? Determine whether the table structure exists 

	stu := &Student{
		Id:   1,
		Name: "yang",
		Age:  22,
	}
	res := conn.Create(stu) // Insert data into the database   , Its return value has only one type , No, error type 
	// notes : If it says stu := Student{...}, Then it is written here Create(&stu) 

	if res.Error != nil {   // Determine whether there is an error in inserting data 
		fmt.Println(res.Error)
	}
}
// After clicking run on the console, the console will not have any output 

2. Some field attributes are inserted

Select Structure part field attribute insertion

stu := &Student{
    Id: 2,
    Name: "xin",
}
res := conn.Select("Id","Name").Create(stu)

3. Batch insert

Creat Batch insert

stu := []Student{
	{Name: "jun", Age: 24},
	{Name: "zhou", Age: 26},
}
  
conn.Create(&stu)// Pass in stu The address of 

from :gorm Data insertion

原网站

版权声明
本文为[Lucky little yellow man]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207041105290028.html

随机推荐