创建表AutoMigrate,并且插入数据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]')
如果将name和email去注释掉,可以看到string类型的是空字符串,另外一个*string类型的是null。所以email的值可以是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 |
+----+------+------+--------+------------+
虽然结构体中没有插入ID的值,但是会在结构体当中生成这个值。
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)}
有两个地方需要注意:
1.指针类型是为了更好的存NULL类型,但是传值的时候,也记得传指针
2.Create按收的是一个指针,而不是值
由于我们传递的是一个指针,调用完Create之后,student这个对象上面就有该记录的信息了,如创建的id
批量插入:需要准备切片或者数组,这里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{})
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)
}