【问题标题】:ERROR: sql: Scan error on column index 11, name "i.end_date": unsupported Scan, storing driver.Value type <nil> into type *time.Time错误:sql:列索引 11 上的扫描错误,名称“i.end_date”:不支持扫描,将 driver.Value 类型 <nil> 存储到类型 *time.Time
【发布时间】:2021-03-11 14:12:33
【问题描述】:

我创建了这样的表格:

CREATE TABLE MyTable
(
    id                  uuid,
    Test                BOOLEAN   NOT NULL,
    end_date            TIMESTAMP NULL DEFAULT NULL,
    PRIMARY KEY (id)
);

我的结构

type Issue struct {
    ID                uuid.UUID
    Test              bool
    EndDate           time.Time `db:"due_date"`
}

现在的情况是,实时数据库中有一些日期没有EndDate,所以现在我在哪里查询以获取all data,我收到了这个错误

ERROR: sql: Scan error on column index 11, name "i.end_date": unsupported Scan, storing driver.Value type &lt;nil&gt; into type *time.Time

我不知道问题出在哪里。

更新

如果我使用 sql.NullTime 然后我做了一个这样的响应模式

return &model.Issue{
        AssetOwnerID: id,
        DueDate :       time.Now().UTC().Truncate(time.Second)
    } 

我收到此错误

 Cannot use 'time.Now().UTC().Truncate(time.Second)' (type Time) as type sql.NullTime

【问题讨论】:

    标签: postgresql go grpc


    【解决方案1】:

    您可以使用sql.NullTime 类型,例如:

    import (
        "database/sql"
    )
    
    
        type Issue struct {
            ID                uuid.UUID
            Test              bool
            EndDate           sql.NullTime `db:"due_date"`
        }
    

    那么,你可以举个例子:

    读操作:

        if i.EndDate.Valid {
            fmt.Println(i.EndDate.Time.Unix())
        } else {
            fmt.Println("nil endDate")
        }
    

    写操作:

            i.EndTime.Valid = true
            i.EndTime.Time = time.Unix(iEndTime, 0)
    

    更新:

    您可以将结构创建为:

    return &model.Issue{
            AssetOwnerID: id,
            DueDate: sql.NullTime{
                Time:  time.Now().UTC().Truncate(time.Second),
                Valid: true,
            }
    

    【讨论】:

    • 我正在使用 EndDate.Unix ,但现在得到了这个 undefined (type sql.NullTime has no field or method Unix)
    • 嗨@FatimaFahad 检查我的更新,希望对您有所帮助
    • 先生在分配此值时遇到问题。 Cannot use 'time.Now().UTC().Truncate(time.Second)' (type Time) as type sql.NullTime我是这样分配当前时间的
    • 嗨@FatimaFahad 我添加了一个读写操作示例
    • 先生,我得到了那个东西,只是坚持我想给它分配一个当天的时间戳。我正在这样做time.Now().UTC().Truncate(time.Second)。但是现在当我这样做时,我遇到了这个问题Cannot use 'time.Now().UTC().Truncate(time.Second)' (type Time) as type sql.NullTim
    猜你喜欢
    • 2019-07-09
    • 2022-01-15
    • 1970-01-01
    • 2019-07-05
    • 2017-12-07
    • 2017-05-13
    • 2019-06-05
    • 2018-06-23
    • 2018-11-03
    相关资源
    最近更新 更多