Home > Article > Backend Development > How to Resolve 'unsupported driver -> Scan pair: []uint8 -> *time.Time' Error When Retrieving Time Data from MySQL in Golang?
Scan pair: []uint8 -> *time.Time" Error When Retrieving Time Data from MySQL in Golang? " /> Scan pair: []uint8 -> *time.Time" Error When Retrieving Time Data from MySQL in Golang? " />
When attempting to retrieve time data from a MySQL database using Golang, you may encounter an error similar to the following:
unsupported driver -> Scan pair: []uint8 -> *time.Time
This error arises because the default behavior of the Go SQL driver does not automatically parse DATE or DATETIME fields from MySQL into the Go time.Time type.
To resolve this issue, you can enable automatic parsing by adding parseTime=true to your database connection string.
db, err := sql.Open("mysql", "root:@/?parseTime=true")
With this setting, the driver will automatically convert DATE and DATETIME values to time.Time objects.
If you encounter specific parsing requirements, you can opt for custom parsing. To do this:
Define a custom type that wraps []byte and includes a Time() method for parsing.
type rawTime []byte func (t rawTime) Time() (time.Time, error) { return time.Parse("15:04:05", string(t)) }
Use your custom type in your scanning code to manually parse the time value.
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())
The above is the detailed content of How to Resolve 'unsupported driver -> Scan pair: []uint8 -> *time.Time' Error When Retrieving Time Data from MySQL in Golang?. For more information, please follow other related articles on the PHP Chinese website!