Home  >  Article  >  Backend Development  >  Scan sql field of DATE type into go struct field

Scan sql field of DATE type into go struct field

王林
王林forward
2024-02-09 08:18:09743browse

将DATE类型的sql字段扫描到go struct字段中

php editor Yuzai Scanning DATE type sql fields into go struct fields is a common task, but many developers encounter difficulties in the implementation process. When dealing with date types, you need to map the date fields in sql with the corresponding fields in go struct. This process requires consideration of date format conversion and how to handle situations such as null values ​​and invalid dates. This article will introduce a simple and effective method to help developers successfully complete this task.

Question content

I have a google bigquery that has a DATE type field, not DATETIME.

How to represent this field in the most natural way in Go?

I've tried:

type Record {
    Date  string `bigquery:"the_date"`
}

An error occurred while executing iterator.Next(&record)<code> of the schema field, the_date of type DATE cannot be assigned to the structure field Date of type string

I have also tried using date of type time.Time as well as type sql.NullTime and the same error is shown for both types as well.

I can't seem to find anything online about putting a simple date value into a base struct member without some kind of string formatting.

Solution

Please trycivil.Date

type Record {
    Date  civil.Date `bigquery:"the_date"`
}

From Go BigQuery documentation p>

STRING      string
BOOL        bool
INTEGER     int, int8, int16, int32, int64, uint8, uint16, uint32
FLOAT       float32, float64
BYTES       []byte
TIMESTAMP   time.Time
DATE        civil.Date
TIME        civil.Time
DATETIME    civil.DateTime
NUMERIC     *big.Rat
BIGNUMERIC  *big.Rat

The above is the detailed content of Scan sql field of DATE type into go struct field. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete