Create table AutoMigrate, and insert data db.Create
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type Student struct {
ID uint `gorm:"size:3"`
Name string `gorm:"size:3"`
Age int `gorm:"size:3"`
Gender bool
Email *string `gorm:"size:32"`
}
func main() {
dsn := "root:7PXjAkY!&nlR@tcp(192.168.11.128:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
db, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{})
db.AutoMigrate(&Student{})
email := "[email protected]"
//添加记录,实例化结构体
s1 := &Student{
Name: "lu",
Age: 21,
Gender: true,
Email: &email,
}
err := db.Debug().Create(s1).Error
fmt.Println(err)
}
[4.019ms] [rows:1] INSERT INTO `students` (`name`,`age`,`gender`,`email`) VALUES ('lu',21,true,'[email protected]')
<nil>
If you comment out name and email, you can see that the string type is an empty string, and the other *string type is null. So the value of email can be Email: nil
//email := "[email protected]"
//添加记录,实例化结构体
s1 := &Student{
//Name: "lu",
Age: 21,
Gender: true,
//Email: &email,
}
[3.829ms] [rows:1] INSERT INTO `students` (`name`,`age`,`gender`,`email`) VALUES ('',21,true,NULL)
mysql> select * from students;
+----+------+------+--------+------------+
| id | name | age | gender | email |
+----+------+------+--------+------------+
| 1 | lu | 21 | 1 | [email protected] |
| 2 | | 21 | 1 | NULL |
+----+------+------+--------+------------+
Although the ID value is not inserted into the structure, this value will be generated in the structure.
s1 := &Student{
//Name: "lu",
Age: 21,
Gender: true,
Email: nil,
}
err := db.Debug().Create(s1).Error
fmt.Printf("%#v \n", s1)
[3.833ms] [rows:1] INSERT INTO `students` (`name`,`age`,`gender`,`email`) VALUES ('',21,true,NULL)
&main.Student{ID:0x5, Name:"", Age:21, Gender:true, Email:(*string)(nil)}
There are two places to pay attention to:
1. The pointer type is to better store NULL types, but when passing values, remember to pass pointers
2.Create accepts a pointer, not a value
Since what we pass is a pointer, after calling Create, the student object will have the record information on it, such as the created id
Batch insertion: slices or arrays need to be prepared, here create needs to pass in slice pointers
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type Student struct {
ID uint `gorm:"size:3"`
Name string `gorm:"size:3"`
Age int `gorm:"size:3"`
Gender bool
Email *string `gorm:"size:32"`
}
func main() {
dsn := "root:7PXjAkY!&nlR@tcp(192.168.11.128:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
db, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{})
db.AutoMigrate(&Student{})
var studentList []Student
for i := 0; i < 10; i++ {
studentList := append(studentList, Student{
Name: fmt.Sprintf("f%d", i),
Age: 21 + i,
Gender: true,
Email: nil,
})
db.Create(&studentList)
}
slist := []Student{
{Name: "cc", Age: 23, Gender: true, Email: nil},
{Name: "xx", Age: 24, Gender: false, Email: nil},
}
db.Create(&slist)
}