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

huangapple go评论72阅读模式
英文:

How to parse *time.Time from sql in golang?

问题

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

尝试执行以下代码:

db.Raw("SELECT * from users;").Scan(&users)
// models.User有一个deleted_at列,类型为*time.Time
// 我在列索引1上得到了Scan错误:不支持的驱动->Scan对:[]uint8->*time.Time

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

User结构体:

type User struct {
    ID        uint64 `gorm:"primary_key"`
    Name      sql.NullString
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *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

得分: 5

lib/pq实现了一个名为NullTime的类型。它为可能为空的time.Time类型定义了一个扫描器接口。你可以将其用作*time.Time的替代。

type NullTime struct {
    Time  time.Time
    Valid bool // 如果Time不为NULL,则Valid为true
}

// Scan实现了Scanner接口。
func (nt *NullTime) Scan(value interface{}) error {
    nt.Time, nt.Valid = value.(time.Time)
    return nil
}

// Value实现了driver Valuer接口。
func (nt NullTime) Value() (driver.Value, error) {
    if !nt.Valid {
        return nil, nil
    }
    return nt.Time, nil
}

你可以在这里找到更多关于NullTime的信息。

英文:

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.

<!-- language: lang-golang -->

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
}

huangapple
  • 本文由 发表于 2015年12月11日 16:43:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/34219285.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定