当我们用golang查询数据库,如果有值为空值,那么我们在scan的时候会报错nil不能转换为你要的类型。这个时候我们有三种解决方案:
1.我们可以在构造结构体时候用指针形式,比如*int,*string,因为我们在 scan 进结构体的时候,如果直接用基本类型,那么等于是将 nil scan 进结构体,自然会报错,但是我们 scan 该类型的空指针,即该类型的空值的时候,就不会报错了。
type Device struct {
Id int `json:"id"`
DeviceGroupId *int `json:"deviceGroupId"`
DeviceGroupName *string `json:"deviceGroupName"`
Name string `json:"name"`
}
2.我们还可以使用sqlNull**,sql.Null***在sql库中,它会把 scan 的结果变成一个对象,第一个值代表你 scan 出来的结果,第二个值为一个bool类型判断它是否为空,如果你 scan 的值为空的时候,如果是string 他就会返回 {“”,false}。
type Device struct {
Id int `json:"id"`
DeviceGroupId sql.NullInt64 `json:"deviceGroupId"`
DeviceGroupName sql.NullString `json:"deviceGroupName"`
Name string `json:"name"`
}
3.我们还可以用数据库自带的判断类型来解决
SELECT id, IFNULL(id, 0) FROM person
SELECT name, COALESCE(name, '') FROM person