英文:
How to parse time from database
问题
我正在使用golang,尝试从MySQL中读取时间,但是遇到了以下错误。
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
我该如何修复这个问题?
英文:
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?
答案1
得分: 78
假设您正在使用go-sql-driver/mysql
,您可以要求驱动程序自动将DATE和DATETIME扫描为time.Time
,只需在连接字符串中添加parseTime=true
。
请参阅https://github.com/go-sql-driver/mysql#timetime-support
示例代码:
db, err := sql.Open("mysql", "root:@/?parseTime=true")
if err != nil {
panic(err.Error()) // 仅作为示例目的。您应该使用适当的错误处理,而不是 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
,则需要自行进行解析。
这是如何进行自定义解析的方法:
首先,我们定义一个包装[]byte的自定义类型,它将自动解析时间值:
type rawTime []byte
func (t rawTime) Time() (time.Time, error) {
return time.Parse("15:04:05", string(t))
}
然后在扫描代码中,我们只需这样做:
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())
英文:
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())
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论