package main
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
type Student struct {
ID int
Name string
Age int
Address string
Class string
}
func main() {
db, err := gorm.Open("mysql", "root:root@/test?charset=utf8&parseTime=True&loc=Local")
if err != nil {
panic(err)
}
db.SingularTable(true)
db.AutoMigrate(Student{})
db.Debug().Save(Student{
ID: 2,
Name: "王二麻子",
Age: 30,
Address: "广东",
Class: "未知",
})
}
/*
(/home/ophelia/Desktop/demo/main.go:25)
[2022-08-07 22:36:09] [0.42ms] UPDATE `student` SET `name` = '王二麻子', `age` = 30, `address` = '广东', `class` = '未知' WHERE `student`.`id` = 2
[0 rows affected or returned ]
(/software/gosdk/go1.19.linux-amd64/go/src/runtime/panic.go:884)
[2022-08-07 22:36:09] [0.42ms] SELECT * FROM `student` WHERE `student`.`id` = 2 ORDER BY `student`.`id` ASC LIMIT 1
[1 rows affected or returned ]
panic: reflect.Value.Addr of unaddressable value [recovered]
panic: reflect.Value.Addr of unaddressable value
goroutine 1 [running]:
github.com/jinzhu/gorm.(*Scope).callCallbacks.func1()
/project/GOPATH/pkg/mod/github.com/jinzhu/gorm@v1.9.16/scope.go:865 +0x74
panic({0x6b9480, 0x7854e0})
/software/gosdk/go1.19.linux-amd64/go/src/runtime/panic.go:884 +0x212
reflect.Value.Addr({0x6eed20?, 0xc0000a0280?, 0xc0001e7cb0?})
/software/gosdk/go1.19.linux-amd64/go/src/reflect/value.go:271 +0x65
github.com/jinzhu/gorm.queryCallback(0xc0000a6980)
/project/GOPATH/pkg/mod/github.com/jinzhu/gorm@v1.9.16/callback_query.go:84 +0x8f3
github.com/jinzhu/gorm.(*Scope).callCallbacks(0xc0000a6980, {0xc0001cd7e0, 0x3, 0x6b9480?})
/project/GOPATH/pkg/mod/github.com/jinzhu/gorm@v1.9.16/scope.go:869 +0x99
github.com/jinzhu/gorm.(*DB).First(0xc00009b450, {0x6eed20?, 0xc0000a0280?}, {0x0, 0x0, 0x0})
/project/GOPATH/pkg/mod/github.com/jinzhu/gorm@v1.9.16/main.go:334 +0x2a5
github.com/jinzhu/gorm.(*DB).FirstOrCreate(0xc0000a6680?, {0x6eed20, 0xc0000a0280}, {0x0, 0x0, 0x0})
/project/GOPATH/pkg/mod/github.com/jinzhu/gorm@v1.9.16/main.go:428 +0x95
github.com/jinzhu/gorm.(*DB).Save(0xc00009a5b0, {0x6eed20, 0xc0000a0280})
/project/GOPATH/pkg/mod/github.com/jinzhu/gorm@v1.9.16/main.go:473 +0x115
main.main()
/home/ophelia/Desktop/demo/main.go:25 +0x145
Process finished with the exit code 2
*/
填坑,Save 或 Create 传入对象指针,即可正常插入数据库
主键一般都是自增的
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
type Student struct {
gorm.Model
Name string
Age int
Address string
Class string
}
func main() {
db, err := gorm.Open("mysql", "root:root@/test?charset=utf8&parseTime=True&loc=Local")
if err != nil {
panic(err)
}
db.SingularTable(true)
db.AutoMigrate(Student{})
stu := Student{
Name: "lili",
Age: 30,
Address: "广东1",
Class: "未知",
}
db.Debug().Save(&stu) //用指针
fmt.Println(stu)
}