本篇文章给大家分享《如何避免 0(零)int 变成 Postgres“空”值并违反“非空”约束?》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。
在 go 中,我将 json 解组/解码为具有 int 类型 id 字段的结构。然后,我尝试使用 go-pg 将此结构插入到 postgresql 数据库中,并将 id 列作为主键(具有非空约束)。第一个条目的 id 为 0。在 postgres 文档中,它指出 0 可以作为主键的值。但是,我不断收到错误消息:
“错误#23502 列“number”中的空值违反了非空约束”。
看起来,当 0 被解组为 int 值时,它变成了 go“零值”。然后将其作为 null 值插入 postgres 中。任何有关我如何避免这种情况的提示将不胜感激。
type Account struct {
Number int `sql:"type:smallint, pk"`
Name string
}
[...]
account := Account{}
err := json.NewDecoder(r.Body).Decode(&account)
[...]
insertErr := pgLayer.db.Insert(&account)
if insertErr != nil {
log.Printf("Error while inserting new item")
return "n/a", insertErr
}解决方案
虽然 go-pg 不是很明显,但您可以使用结构标记 sql:",notnull" 来显示 go 空值(""、0、[] 等)是允许的并且应该不被视为 sql null。
您可以在Features list中看到它。
对于你的情况,我会将其更改为:
type Account struct {
Number int `sql:"type:smallint,pk,notnull"`
Name string
}
今天关于《如何避免 0(零)int 变成 Postgres“空”值并违反“非空”约束?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
