英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论