将Go的time.Time转换为PostgreSQL的timestamptz并使用time.Now()保存时遇到问题。

huangapple go评论101阅读模式
英文:

Go time.Time to postgresql timestamptz not able to save with time.Now()

问题

你好,我是你的中文翻译助手。以下是你要翻译的内容:

嗨,我是Go语言的新手,我正在尝试为一个time.Time类型的变量插入time.Now()的值。奇怪的是,我既没有收到错误,也没有进行提交处理,而是在尝试插入时代码的执行被停止了。请问有人可以帮助我,我应该尝试什么值?

数据库表结构如下:
alter table abc add column created timestamptz NULL;

结构体定义如下:
struct {
created time.Time db:"created"
}

在插入之前设置的值为:
created = time.Now()

我期望数据库能保存这条新记录。

英文:

Hi I am new to golang and I am trying to insert a time.Now() value for a time.Time type of variable The weired part is that i am neither getting an error nor having the commit proccessed rather the execution of the code is been stopped when i try to insert it. Can someone please help me what should be the value that I should be trying?

db:
alter table abc add column created timestamptz NULL;

struct {
created time.Time db:"created"
}

value been set before the insert is
created = time.Now()

I expect the db to be saved with the new record

答案1

得分: 2

为了使任何外部库能够查看您的结构字段,它们需要被导出,即名称必须以大写字母开头。

由于您的定义将created时间定义为小写字母,只有包内的代码才能看到该字段。这就是为什么您的数据库接口将"created"设置为NULL的原因-就它所知,从未为该字段提供过任何值。

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

注意:如果您正在使用GORM与数据库进行交互,它实际上默认支持您尝试的操作,只需将结构字段命名为CreatedAt:https://gorm.io/docs/conventions.html#CreatedAt

英文:

In order for any external library to be able to look at your struct fields, they need to be exported, i.e. the name must start with a capital letter.

Since your definition defines the created time with a lower case letter, only code inside your package can see that field. This is why your database interface is setting "created" to NULL - as far as it knows, no value was ever provided for that field.

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

Note: if you happen to be using GORM to interface with your database, it actually supports what you are trying to do by default, simply by naming the struct field CreatedAt: https://gorm.io/docs/conventions.html#CreatedAt

huangapple
  • 本文由 发表于 2023年1月14日 02:46:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75113333.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定