我在使用Go向psql数据库插入时间戳时遇到了问题,我用这一行形成我的时间戳:
datetime := currentTime.Format("02-01-2006 15:04:05")
我的SQL查询是:
SqlStatement := `
INSERT INTO readings (date, temp, humi)
VALUES ($1, $2, $3)`
然后我对psql DB的调用是:
_, err = Db.Exec(SqlStatement, datetime, temp, humi)
(如你所见,这里还有一些其他变量,但它们没有造成任何问题。)
当我执行我的代码时,我会得到以下错误:
pq: date/time field value out of range: "21-11-2018 22:19:59"
据我所知,这意味着格式不正确。
然而,当我直接向psql控制台输入完全相同的查询时,它成功地将记录(行)添加到了表中。
INSERT INTO readings (date, temp, humi) VALUES ('02-01-2006 15:04:05', 20, 30);
附带注意:在我将列类型从字符(20)更改为时间戳之前,这段代码还是工作正常的,我甚至尝试将强制转换包含在SQL中,但我得到了相同的错误。
I can see that datetime
variable is string
type. I don't know why you must convert time.Time
to string
before exec query.
If define date
column in readings
table is TIMESTAMP
, you can exec query like thisDb.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.
Wierd.