如何从数据库解析时间 [英] How to parse time from database
问题描述
我正在使用golang,并且尝试从mysql读取时间,并且遇到以下错误.
I am using golang and I am trying to read time from mysql and I am getting the following error.
var my_time time.Time
rows, err := db.Query("SELECT current_time FROM table")
err := rows.Scan(&my_time)
我得到的错误是
unsupported driver -> Scan pair: []uint8 -> *time.Time
我该如何解决?
推荐答案
假设您使用的是go-sql-driver/mysql
,则可以通过将parseTime=true
添加到连接中,要求驱动程序自动将DATE和DATETIME扫描到time.Time
.字符串.
Assuming you're using the go-sql-driver/mysql
you can ask the driver to scan DATE and DATETIME automatically to time.Time
, by adding parseTime=true
to your connection string.
请参见 https://github.com/go-sql-driver/mysql#timetime-support
示例代码:
db, err := sql.Open("mysql", "root:@/?parseTime=true")
if err != nil {
panic(err.Error()) // Just for example purpose. You should use proper error handling instead of panic
}
defer db.Close()
var myTime time.Time
rows, err := db.Query("SELECT current_timestamp()")
if rows.Next() {
if err = rows.Scan(&myTime); err != nil {
panic(err)
}
}
fmt.Println(myTime)
请注意,这适用于current_timestamp
,但不适用于current_time
.如果必须使用current_time
,则需要自己进行解析.
Notice that this works with current_timestamp
but not with current_time
. If you must use current_time
you'll need to do the parsing youself.
首先,我们定义一个包装[] byte的自定义类型,该类型将自动解析时间值:
First, we define a custom type wrapping []byte, that will automatically parse time values:
type rawTime []byte
func (t rawTime) Time() (time.Time, error) {
return time.Parse("15:04:05", string(t))
}
在扫描代码中,我们只是这样做:
And in the scanning code we just do this:
var myTime rawTime
rows, err := db.Query("SELECT current_time()")
if rows.Next() {
if err = rows.Scan(&myTime); err != nil {
panic(err)
}
}
fmt.Println(myTime.Time())
这篇关于如何从数据库解析时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!