programing

How to parse time from database

newstyles 2023. 10. 26. 20:48

How 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 am getting is

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

How can I fix this?

당신이 사용한다고 가정할 때go-sql-driver/mysql운전자에게 DATE와 DATEIME을 자동으로 스캔하도록 요청할 수 있습니다.time.Time, 덧셈으로parseTime=true연결 문자열에 연결합니다.

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)

이 기능은 다음과 같이 작동합니다.current_timestamp함께는 아니지만current_time. 꼭 사용해야 하는 경우current_time직접 파싱을 해봐야 할 겁니다

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())

ReferenceURL : https://stackoverflow.com/questions/29341590/how-to-parse-time-from-database