[英]How to insert timestamp to postgreSQL database
I have a problem inserting timestamp to my psql database using Go. 我使用Go将时间戳插入psql数据库时遇到问题。
I form my timestamp with this line: 我用这一行形成时间戳:
datetime := currentTime.Format("02-01-2006 15:04:05")
My sql query is: 我的SQL查询是:
SqlStatement := `
INSERT INTO readings (date, temp, humi)
VALUES ($1, $2, $3)`
And then my call to the psql DB is: 然后,我对psql DB的调用是:
_, err = Db.Exec(SqlStatement, datetime, temp, humi)
(As you can see I have some other variables here but they are not causing any problems.) (如您所见,我在这里还有其他一些变量,但它们不会引起任何问题。)
When I execute my code I get this error: 当我执行代码时,出现以下错误:
pq: date/time field value out of range: "21-11-2018 22:19:59"
pq:日期/时间字段值超出范围:“ 21-11-2018 22:19:59”
Which as I understand it means that the format is not correct. 据我了解,这表示格式不正确。
YET when I input exact same query directly to psql console it successfully adds record(line) to the table. 还可以,当我直接向psql控制台输入完全相同的查询时,它成功将record(line)添加到表中。
INSERT INTO readings (date, temp, humi) VALUES ('02-01-2006 15:04:05', 20, 30);
Side note: This code worked ok before I changed column type from character(20) to timestamp, I even tried incorporating CAST in the SQL but I got the same error. 旁注:在将列类型从character(20)更改为时间戳之前,此代码可以正常工作,我什至尝试将CAST合并到SQL中,但遇到相同的错误。
I can see that datetime
variable is string
type. 我可以看到
datetime
变量是string
类型。 I don't know why you must convert time.Time
to string
before exec query. 我不知道为什么必须在执行查询之前将
time.Time
转换为string
。
If define date
column in readings
table is TIMESTAMP
, you can exec query like this 如果
readings
表中的定义date
TIMESTAMP
,则可以像这样执行查询
Db.Exec(SqlStatement, currentTime, temp, humi)
Solved it by adding 通过添加解决
SET datestyle TO dmy;
Before each 每个之前
_, err = Db.Exec(SqlStatement, datetime, temp, humi)
So now I have two Db.Exec functions in a row, one is sending "SET datestyle TO dmy" and the other is this one that is sending actual data. 因此,现在我连续有两个Db.Exec函数,一个正在发送“ SET datestyle TO dmy”,另一个正在发送实际数据。
Wierd. 怪异的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.