gpt4 book ai didi

mysql - 从 Go 中的 sql 中获取 nil 值

转载 作者:IT王子 更新时间:2023-10-29 01:57:18 25 4
gpt4 key购买 nike

假设我有一个结构Profile 和sql 表profiles

type Profile struct {
ID int `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Age int `json:"age"`
}

然后,我从 profiles 表中获取一条记录,分配到 Profile 结构中。

这些字段是allow null,所以我使用了sql.NullStringsql.NullInt64pq.NullTime 在分配给结构之前检查有效值。

// ... DB.Query(...)
// ... rows.Next()
// ... rows.Scan()
// ...
if firstName.Valid {
p.FirstName = firstName.String
}
if lastName.Valid {
p.LastName = lastName.String
}
if age.Valid {
p.Age = age.Int64
}
// ...

如果我有超过 10 个表,每个表有超过 30 列,我必须一次又一次地检查所有变量。这使得代码变得丑陋,有人有任何让它变得漂亮的建议吗?

最佳答案

你根本不应该这样过牌。可空类型旨在直接在结构中使用:

type Profile struct {
ID sql.NullInt64 `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
FirstName sql.NullString `json:"first_name"`
LastName sql.NullString `json:"last_name"`
Age sql.NullInt64 `json:"age"`
}

然后使用例如 product.FirstName.String() 访问这些值。没有理由检查 product.FirstName.Valid 除非你真正关心 nil 和空值之间的区别(在你的问题的例子中,你显然不我不关心这个区别)。

在某些情况下可能更合适的替代方法是只使用指针:

type Profile struct {
ID *int `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
FirstName *string `json:"first_name"`
LastName *string `json:"last_name"`
Age *int `json:"age"`
}

当然,任何使用这些变量的代码都必须取消引用它们,并检查 nil,因此这可能并不总是最理想的,具体取决于您如何使用这些值。

第三种选择,如果您从不关心 NULL 值和空值之间的区别,那就是创建您自己的类型,将它们一视同仁。示例:

type myString string

func (s *myString) Scan(src interface{}) error {
if src == nil {
return nil
}
if value, ok := src.(string); ok {
*s = value
return nil
}
return fmt.Errorf("Unsupported type for myString: %T", src)
}

关于mysql - 从 Go 中的 sql 中获取 nil 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48416958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com