Scan sql field of DATE type into go struct field

王林
Release: 2024-02-09 08:18:09
forward
739 people have browsed it

将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"`
}
Copy after login

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"`
}
Copy after login

From Go BigQuery documentation

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

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!

source:stackoverflow.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template