Database Golang DB反序列化/序列化方法(数据库/sql顶部的sqlx)

Database Golang DB反序列化/序列化方法(数据库/sql顶部的sqlx),database,go,serialization,struct,casting,Database,Go,Serialization,Struct,Casting,我在数据库中有一个Timestamp列,还有一个类型为int64的结构,它应该将该列作为整数时间戳加载 查询: select date from table; 错误: sql: Scan error on column index 1, name "date": converting driver.Value type time.Time ("2019-04-14 21:49:59.159317 +0000 +0000") to a int64: invalid syntax 有没有办法在结

我在数据库中有一个
Timestamp
列,还有一个类型为
int64
的结构,它应该将该列作为整数时间戳加载

查询:

select date from table;
错误:

sql: Scan error on column index 1, name "date": converting driver.Value type time.Time ("2019-04-14 21:49:59.159317 +0000 +0000") to a int64: invalid syntax

有没有办法在结构上定义序列化方法,而不是在查询级别(
extract epoch…
)将时间戳强制转换为
int64

您需要一个自定义
int64
类型,以便让它实现
sql.Scanner
接口

type Timestamp int64

func (ts *Timestamp) Scan(src interface{}) error {
    switch v := src.(type) {
    case time.Time:
        *ts = Timestamp(v.Unix())
    case []byte:
        // ...
    case string:
        // ...
    }
    return nil
}
使用此选项,您可以在扫描结果时使用转换:

type Record struct {
    Date int64
}

var r Record
if err := db.QueryRow("select data from table").Scan((*Timestamp)(&r.Date)); err != nil {
    panic(err)
}
或者,您可以在结构定义中更改字段的类型,然后直接扫描到字段中:

type Record struct {
    Date Timestamp
}

var r Record
if err := db.QueryRow("select data from table").Scan(&r.Date); err != nil {
    panic(err)
}