如何从golang中的sql解析* time.Time?

时间:2015-12-11 08:43:19

标签: go sqlite

使用gormgo-sqlite3。使用gorm.Open("sqlite3", "/dev.db?charset=utf8&parseTime=true")打开我的数据库。

尝试执行

db.Raw("SELECT * from users;").Scan(&users)
// models.User has a deleted_at column that is of the type *time.Time
// I am getting Scan error on column index 1: unsupported driver -> Scan pair: []uint8 -> *time.Time

如何将sql解析为* time.Time?

用户结构

type User struct {
    ID        uint64 `gorm:"primary_key"`
    Name      sql.NullString
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *time.Time
}

1 个答案:

答案 0 :(得分:5)

lib / pq为此实现NullTime类型。它定义了time.Time类型的扫描仪接口,该类型可以为null。您可以使用它来换取*time.Time

type NullTime struct {
    Time  time.Time
    Valid bool // Valid is true if Time is not NULL
}

// Scan implements the Scanner interface.
func (nt *NullTime) Scan(value interface{}) error {
    nt.Time, nt.Valid = value.(time.Time)
    return nil
}

// Value implements the driver Valuer interface.
func (nt NullTime) Value() (driver.Value, error) {
    if !nt.Valid {
        return nil, nil
    }
    return nt.Time, nil
}