英文:
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
}
如果 Valid
为 true
,那么你将在 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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论