使用gorm将一条数据插入mysql数据库。

huangapple go评论68阅读模式
英文:

Insert a piece of data into mysql by using gorm

问题

我想将一条数据插入到我的数据库(MySQL)中,但是失败了。

错误1364:字段'envelopeId'没有默认值。

我发现有些人说这是因为主键是int类型,并且没有设置为自动递增,但实际上它是varchar类型。

var envelope Envelope
envelope = Envelope{
    "100000000001",
	1,
	0,
	100,
}
fmt.Println(db.Create(&envelope).Error)
英文:

I want to insert a piece of data into my database(MySQL). However, I failed.

Error 1364: Field 'envelopeId' doesn't have a default value.

I found that some people say that this is because the primary key is of int type and not set to auto-increment, but this is actually a varchar type.

var envelope Envelope
envelope = Envelope{
    "100000000001",
	1,
	0,
	100,
}
fmt.Println(db.Create(&envelope).Error)

答案1

得分: 1

这个错误意味着你正在尝试将一个NULL值插入到一个非空字段中,而且由于没有指定默认值,所以会报错。我猜"100000000001"是你的主键,如果是这样的话,你需要检查结构体中是否设置了该字段的gorm:"column:envelopeId"标签。根据GORM的约定,列名应该使用蛇形命名法,而不是你在数据库中使用的驼峰命名法。

英文:

This error means that you are trying to insert an NULL value into a non-nullable field, and since there is also no default value specified it gives you and error. I assume "100000000001" is your primary key, if this is the case, it is set in your struct and you need to check that that field has the gorm:"column:envelopeId" tag set. By convention GORM will use snake case for column names, not camel case like you have in your DB.

huangapple
  • 本文由 发表于 2021年11月7日 14:38:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/69870294.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定