【问题标题】:How return null value to empty string field如何将空值返回到空字符串字段
【发布时间】:2019-08-04 14:42:14
【问题描述】:

我在 Golang 应用程序中有这样的struct

type Employee struct {
    ID int `json:"employee_id"`
    Email *string `json:"employee_email"`
    LastName *string `json:"employee_last_name"`
    FirstName *string `json:"employee_first_name"`
    Sex *string `json:"employee_sex"`
}

此结构的某些字符串字段可以为空。如果我使用*string 应用程序返回我""。如果使用sql.NullString,它会返回例如这样的结果:

"employee_last_name": {
    String: "",
    Valid: true
}

我想显示null 是字符串字段为空。

documentation我找到了这样的代码:

type NullString struct {
    String string
    Valid  bool
}

func (ns *NullString) Scan(value interface{}) error {
    if value == nil {
        ns.String, ns.Valid = "", false
        return nil
    }
    ns.Valid = true
    return convertAssign(&ns.String, value)
}

func (ns NullString) Value() (driver.Value, error) {
    if !ns.Valid {
        return nil, nil
    }
    return ns.String, nil
}

据我了解,这段代码可以帮助我解决问题,对吧?!我需要在我的应用程序中导入什么才能使用convertAssign 函数?

【问题讨论】:

  • 我假设您是从 SQL 源获取数据?并且有问题的表数据有一个空值,您知道为什么空值不显示为gonil 值?这是对您问题的正确评估吗?
  • 如果是 SQL - 请发布数据库驱动程序。 MySQL、SQLite 等?在 RowScan 期间,可能需要启用驱动程序选项以支持 NULL 值。
  • @colminator 你好!是的,你是对的。例如,我注意到*int 回复了我null。为什么*string 只回复我"" 而不是null。事实上,在数据库中,column 具有空值。我可以更改此默认行为吗?
  • @colminator 请注意,这与goracle 无关,正如您已经通过引用文档在答案中指出的那样,这是oracle 本身的问题,而不是驱动程序的问题。如果 oracle 在内部将空字符串更改为 NULL,则驱动程序的作者几乎无能为力。还有stackoverflow.com/a/13278879/965900
  • @colminator 没有人说 oracle db 不支持 NULL。

标签: go


【解决方案1】:

在 Go 语言规范中,nil 不是类型 string 的有效值。默认的零值为""

The top answer for this question goes into more detail.

【讨论】:

  • 您好!谢谢你的信息。例如,我注意到*int 回复了我null。同时*string 只回复我"" 而不是null。实际上在数据库列中具有null 值。是否可以更改此默认行为?
【解决方案2】:

编辑:

根据oracle go driver docs,你想做的事情是不可能的:

sql.NullString

不支持 sql.NullString:Oracle DB 不支持 区分空字符串 ("") 和 NULL

原答案:

需要有关您要连接的 SQL 数据库类型的更多详细信息。我知道 go SQLite3 pkg - github.com/mattn/go-sqlite3 - 支持为 *string 类型的值设置 nil

检查您用于连接数据库的驱动程序的详细信息。以 MySQL 为例,默认情况下未设置将 SQL 日期字段放入 go 的本机 time.Time 结构类型 - 它必须是 turned on at the driver level

【讨论】:

  • 您好!谢谢您的回答。就我而言,我使用 Oracle 数据库。我使用goracle 包来处理数据库。您现在还有其他想法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-19
相关资源
最近更新 更多