Home >Backend Development >Golang >Go time.Time to postgresql timestamptz cannot be saved using time.Now()

Go time.Time to postgresql timestamptz cannot be saved using time.Now()

WBOY
WBOYforward
2024-02-05 22:42:081247browse

转到 time.Time 到 postgresql timestamptz 无法使用 time.Now() 保存

Question content

Hi, I am new to golang and I am trying to insert time.Now() value. Variable of type Time The strange thing is that I neither receive an error nor the commit is processed, instead the execution of the code is stopped when I try to insert it. Can someone help me see what value I should try?

database: ALTER TABLE abc ADD COLUMN CREATED timestamptz NULL;

Structure{ Creation time. Time db:"Created" }

The value that was set before inserting Create = time.Now()

I want the database to be saved with the new records


Correct Answer


In order for any external library to be able to view your struct fields they need to be exported i.e. the names must Start with a capital letter.

Since your definition defines the created time in lowercase letters, only code within the package will see this field. That's why your database interface sets "created" to null - as far as it knows, no value is provided for the field.

type Foo struct { 
    Created time.Time db:"created"
}

Note: If you happen to be using gorm to interact with the database, it actually supports what you are trying to do by default, just name the struct fields createdat: https://gorm.io /docs/conventions.html#createdat

The above is the detailed content of Go time.Time to postgresql timestamptz cannot be saved using time.Now(). 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