golang 从mysql取datetime类型数据
通过golang从mysql中查询datetime字段,本想参考之前普通类型查询,只要将变量类型修改为time.Time就可以:
rows, err := db.Query("select login_time from user where id=1")
for rows.Next() {
var lastLoginTime time.Time
err = rows.Scan(&lastLoginTime)
if err != nil {
panic(err)
}
fmt.Println(lastLoginTime)
}
运行代码并没有得到预期的结果,运行出错,err信息为:
sql: Scan error on column index 1: unsupported driver -> Scan pair: []uint8 -> *time.Time
通过google得出的解决方法是先将datetime的字面值赋值给string变量。然后通过time.Parse(layout, value)转换为time.Time类型
var lastLoginTime string
err = rows.Scan(&lastLoginTime)
loginTime, _ := time.Parse("2006-01-02 15:04:05", lastLoginTime)
fmt.Println(loginTime)
运行结果为
2015-05-22 13:22:51 +0000 UTC