我正在尝试使用 gorm 将名为 Teacher 的结构插入到 sqlite 数据库中,当我调用创建函数时,我收到错误消息:
INSERT INTO `teachers` (`name`,`department`,`password`) VALUES RETURNING `id`
panic: unsupported data
这是我的老师结构:
type Teacher struct {
Id int `json:"id" db:"id" gorm:"primarykey"`
Name string `json:"name" db:"name"`
Department string `json:"department" db:"department"`
Password string `json:"-" db:"password"`
}
这就是我插入的方式:
data := Teacher{
Id: 0,
Name: "JohnDoe",
Department: "ComputerScience",
Password: "12312312312321",
}
DB.Create(&data)
编辑:
更多用于理解的代码:
main.go:
t := models.Teacher{
Id: 0,
Name: "JohnDoe",
Department: "ComputerScience",
Password: "12312312312321",
}
t.CreateTeacher()
老师.去:
type Teacher struct {
Id int `json:"id" db:"id" gorm:"primarykey"`
Name string `json:"name" db:"name"`
Department string `json:"department" db:"department"`
Password string `json:"-" db:"password"`
}
func (teacher Teacher) CreateTeacher() error {
fmt.Println(teacher)
err := database.Insert(teacher)
if err != nil {
panic(err)
}
return nil
}
数据库.go:
func ConnectDatabase() error {
var err error
DB, err = gorm.Open(sqlite.Open("./cisl-database.db"), &gorm.Config{})
if err != nil {
return err
}
return nil
}
func Insert(data interface{}) error {
fmt.Print(data)
err := ConnectDatabase()
if err != nil {
return err
}
DB.AutoMigrate(&data)
if err := DB.Create(&data).Error; err != nil {
return err
}
return nil
}
// ...
func Insert(data interface{}) error {
// ...
因为你将interface{}类型传递给gorm,它无法处理它。你需要更改为
func Insert(data Teacher) error {
顺便说一句,我认为代码不是最佳实践:)
也许您可以考虑仅调用数据库实例
Create(&data)
或其他操作,例如Transaction
等。