Postgres列时间戳的类型为timestamp,但表达式的类型为text



我刚刚开始使用PostgreSQL开发使用时间刻度的时间序列数据库。在我使用时间刻度之前,我想设置一个插入数据的小测试。在将c#中的数据插入postgres数据库表时,我遇到了以下错误:

column "timestamp" is of type timestamp without time zone but expression is of type text

我在查阅postgres的文档,但找不到解决方案。

这是我的桌子:

CREATE TABLE measurement_ms (
id SERIAL PRIMARY KEY,
value VARCHAR(255) NULL,
timestamp TIMESTAMP(6) NULL,
machine_id INT NOT NULL,
measurement_type_id INT NOT NULL,
point_of_measurement_id INT NOT NULL,
FOREIGN KEY (machine_id) REFERENCES machine (id),
FOREIGN KEY (measurement_type_id) REFERENCES measurement_type (id),
FOREIGN KEY (point_of_measurement_id) REFERENCES point_of_measurement (id)
);

这是c#中我用来将数据插入表中的代码:

NpgsqlCommand addMeasurementQuery = new NpgsqlCommand("INSERT INTO measurement_ms (value, timestamp, machine_id, measurement_type_id, point_of_measurement_id) values(@value, @timestamp, @machine_id, @measurement_type_id, @point_of_measurement_id)", connection);
addMeasurementQuery.Parameters.AddWithValue("@value", value);
addMeasurementQuery.Parameters.AddWithValue("@timestamp", timestamp.ToString("YYYY-MM-DD HH:MI:SS:MS"));
addMeasurementQuery.Parameters.AddWithValue("@machine_id", fk_machineID);
addMeasurementQuery.Parameters.AddWithValue("@measurement_type_id", fk_pointOfMeasurementID);
addMeasurementQuery.Parameters.AddWithValue("@point_of_measurement_id", fk_measurementTypeID);
addMeasurementQuery.ExecuteNonQuery();

有人能推动我们朝着正确的方向解决这个问题吗?我想我可能格式的时间戳不正确,但我不确定。

经过对这个问题的进一步研究,我找到了以下解决方案:我试过丹在评论中说的话,但没能奏效。

NpgsqlCommand addMeasurementQuery = new NpgsqlCommand("INSERT INTO verbruggen_iot.measurement_ms (value, timestamp, machine_id, measurement_type_id, point_of_measurement_id) values(@value, CAST(@timestamp as timestamp), @machine_id, @measurement_type_id, @point_of_measurement_id)", connection);

问题中的查询与此查询的区别在于,我以以下方式投射时间戳:

CAST(@timestamp as timestamp)

使用上面的强制转换,我仍然能够执行其余的代码。

最新更新