0

我收到此错误并尝试了 Internet 和 stackoverlow 中可用的所有内容来解决此问题。我试图在使用 sqlx 包连接 MySQL db 并扫描结果后运行查询。我已经尝试过针对类似问题共享的解决方案,但对我没有任何帮助。

type Trip struct {
    ID                 int       `db:"id"`
    Type           int       `db:"type"`
    DID           int       `db:"did"`
    DUID       int       `db:"duid"`
    VID          int       `db:"vid"`
    Sts             string    `db:"sts"`
    AM      int       `db:"am"`
    Sdate null.Time `db:"sdate"`
}


func GetTripByID(db sqlx.Queryer, id int) (*Trip, error) {
    row := db.QueryRowx("select ID,Type,DID,DUID,VID,Sts,AM,Sdate from mytbl where ID=123", id)
    var t Trip
    err := row.StructScan(&t)
    if err != nil {
        fmt.Println("Error during struct scan")
        return nil, err
    }
    return &t, nil
}

我得到的确切错误是

恐慌:sql:列索引6上的扫描错误,名称“sdate”:null:无法将类型[]uint8扫描为null。时间:[50 48 49 56 45 49 50 45 48 55 32 48 50 58 48 56 58 53 49]

语法方面,查询工作得很好,当我在 sql 工作台中运行它时,我得到了结果。我还尝试了 ParseTime=true 作为链接之一的建议。

4

2 回答 2

2

尝试对包“database/sql”中的空值使用特殊类型

例如,当 db 中的 text 或 varchar 可以为 null 时,使用 sql.NullString 作为 var 类型。

于 2019-01-10T15:18:56.420 回答
1

如上所述,我对“Sdate”列进行了空处理

// NullTime defining nullTime
type NullTime mysql.NullTime

// Scan implements the Scanner interface for NullTime
func (nt *NullTime) Scan(value interface{}) error {
    var t mysql.NullTime
    if err := t.Scan(value); err != nil {
        return err
    }

    // if nil then make Valid false
    if reflect.TypeOf(value) == nil {
        *nt = NullTime{t.Time, false}
    } else {
        *nt = NullTime{t.Time, true}
    }

和结构的变化

type Trip struct {
    ID                 int       `db:"id"`
    Type           int       `db:"type"`
    DID           int       `db:"did"`
    DUID       int       `db:"duid"`
    VID          int       `db:"vid"`
    Sts             string    `db:"sts"`
    AM      int       `db:"am"`
    Sdate NullTime `db:"sdate"`
}

因此解决方案不仅是定义用于处理 null 的结构,而且还实现了扫描仪接口。

于 2019-01-11T06:56:09.027 回答