Go to Parse Time From Database

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 get is

  unsupported driver -> Scan pair: []uint8 -> *time.Time 

How can i fix this?

+5
source share
1 answer

Assuming you are using go-sql-driver/mysql , you can ask the driver to automatically scan DATE and DATETIME for time.Time by adding parseTime=true to your connection string.

See https://github.com/go-sql-driver/mysql#timetime-support

Code example:

 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) 

Note that this works with current_timestamp , but not with current_time . If you must use current_time , you will need to parse.

Here's how you do your own parsing:

First, we define a byte for a personalized type [], which will automatically analyze the time values:

 type rawTime []byte func (t rawTime) Time() (time.Time, error) { return time.Parse("15:04:05", string(t)) } 

And in the scan 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()) 
+14
source

Source: https://habr.com/ru/post/1216443/


All Articles