Home > Backend Development > Golang > How to Parse Time from a MySQL Database in Go?

How to Parse Time from a MySQL Database in Go?

Barbara Streisand
Release: 2024-11-11 00:28:03
Original
997 people have browsed it

How to Parse Time from a MySQL Database in Go?

Parsing Time from a MySQL Database in Go

When attempting to retrieve a time value from a MySQL database using Go, you may encounter an "unsupported driver -> Scan pair" error. This issue stems from the default behavior of Go's MySQL driver not automatically converting DATE and DATETIME values to time.Time objects.

To resolve this issue, add parseTime=true to your MySQL connection string. This parameter instructs the driver to perform the necessary parsing for you.

Example

db, err := sql.Open("mysql", "root:@/?parseTime=true")
if err != nil {
    panic(err)
}
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)
Copy after login

Custom Parsing

If you cannot use current_timestamp and must use current_time, you'll need to perform the parsing yourself.

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())
Copy after login

This custom parsing type converts the retrieved byte slice into a time.Time object using a specific time format ("15:04:05" in this case).

The above is the detailed content of How to Parse Time from a MySQL Database in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template