从MySQL中使用golang检索时间.time的日期时间

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

retrieving datetime from mysql in time.time in golang

问题

我在我的数据库(mySQL)中存储了一个名为last_activity的日期时间字段,值为2017-06-12 11:07:09

我在OpenDB中使用了参数parseTime=True

问题是输出结果为:last activity: {63632862429 0 <nil>},而不是2017-06-12 11:07:09

我做错了什么?

谢谢

type DateType time.Time

type User struct {
    LastActivity DateType
}

func (stUser *User) GetUserDataByLogin(login string) {
    db := OpenDB()
    defer db.Close()

    // 测试与数据库的连接
    err := db.Ping()
    checkErr(err)

    err = db.QueryRow("SELECT last_activity FROM users WHERE login = ?", login).Scan(&stUser.LastActivity)

    if err != nil {
        if err == sql.ErrNoRows {
            // 没有行,但没有发生错误
        } else {
            log.Fatal(err)
        }
    }

    fmt.Println("last activity:", stUser.LastActivity)
}
英文:

i have stored on my database (mySQL) this datatime field, last_activity: 2017-06-12 11:07:09

im using the param parseTime=True on my OpenDB

the problem is that the output is: last activity: {63632862429 0 <nil>}
instead of 2017-06-12 11:07:09

what am i doing wrong?

thanks

type DateType time.Time

type User struct {
	LastActivity DateType
}


func (stUser *User) GetUserDataByLogin(login string) {

db := OpenDB()

defer db.Close()

// Test the connection to the database
err := db.Ping()
checkErr(err)

err = db.QueryRow("SELECT  last_activity FROM users WHERE login = ?", login).Scan(&stUser.LastActivity)

if err != nil {
	if err == sql.ErrNoRows {
		// there were no rows, but otherwise no error occurred
	} else {
		log.Fatal(err)
	}
}

fmt.Println("last activity:", stUser.LastActivity)

}

答案1

得分: 3

你必须像这样声明DateType.String()方法:

func (t DateType) String() string {
    return time.Time(t).String()
}

根据语言规范

声明的类型不会继承绑定到现有类型的任何方法。

英文:

You must declare DateType.String() method like this:

func (t DateType) String() string {
    return time.Time(t).String()
}

From Language Specification:

> The declared type does not inherit any methods bound to the existing type

答案2

得分: 0

time.Time 是一个可为空的类型。你需要预先考虑到这一点,并使用类似于 pq 包和 NullTime 类型而不是 time.Time

pq.NullTime 是一个结构体:

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

如果 Validtrue,那么你将在 Time 中得到一个结果。

参考链接:https://godoc.org/github.com/lib/pq#NullTime

英文:

time.Time is a nullable type. You got to anticipate that and use somethink like the pq package and the NullTime type instead of time.Time.
cf : https://godoc.org/github.com/lib/pq#NullTime

pq.NullTime is a structure :

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

If Valid is True then you'll got a result in Time.

huangapple
  • 本文由 发表于 2017年6月12日 19:49:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/44498738.html
匿名

发表评论

匿名网友

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

确定