drkj41932 2015-12-11 08:43
浏览 257

如何从Golang中的SQL解析* time.Time?

Using gorm and go-sqlite3. Opening my db using gorm.Open("sqlite3", "/dev.db?charset=utf8&parseTime=true").

Trying to execute

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

How do I parse sql into *time.Time?

User struct

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

1条回答 默认 最新

  • dongxin1980 2015-12-12 23:03
    关注

    lib/pq implements a NullTime type for that. It defines a scanner interface for a time.Time type that may be null. You can use it in exchange to *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
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况