问题描述
$ b
var my_time 我使用golang,并且正在尝试从mysql读取时间,并且出现以下错误。 time.Time
rows,err:= db.Query(SELECT current_time FROM table)
err:= rows.Scan(&my_time)
我得到的错误是
不受支持的驱动程序 - >扫描对:[] uint8 - > * time.Time
如何解决这个问题?
parseTime = true
自动添加到 time.Time
中。 请参阅
示例代码:
db ,err:= sql.Open(mysql,root:@ /?parseTime = true)
pre>
if err!= nil {
panic(err.Error())//举个例子目的。您应该使用适当的错误处理而不是恐慌
}
defer db.Close()
var myTime time.Time $ b $ 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
,您需要自行解析。
这就是自定义解析:
首先,我们定义一个自定义类型wrapping []字节,它将自动分析时间值:
<$ p $($)$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $' 04:05,string(t))
}
在扫描代码中,我们只需做到这一点:
var myTime rawTime
rows,err:= db.Query(SELECT current_time() )
如果rows.Next(){
if err = rows.Scan(& myTime); err!= nil {
panic(err)
}
}
fmt.Println(myTime.Time())
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)
The error I am getting is
unsupported driver -> Scan pair: []uint8 -> *time.Time
How can I fix this?
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.
See https://github.com/go-sql-driver/mysql#timetime-support
Example code:
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)
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.
This is how you do custom parsing:
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())
这篇关于从数据库中解析时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!