在 C# 的查询中插入带时区的时间戳

Insert timestamp with timezone in query from C#

我已将以下 table 存入我的 PostgreSQL 数据库:

CREATE TABLE rates
(
  source character varying(5) NOT NULL,
  target character varying(5) NOT NULL,
  "from" timestamp with time zone NOT NULL,
  "to" timestamp with time zone,
  exchange_rate numeric(10,10) NOT NULL,
)

我有一个带有一些占位符的文本查询,用于在其中插入一行 table:

INSERT INTO public.rates 
      (source, target, from, to , exchange_rate)
VALUES("{0}" , "{1}" , {2} , {3}, {4}          );

我不知道如何替换占位符 {2}{3} 才能给出正确的时区时间戳。

我需要在 {2} 中输入我指定的带有 UTC 时区的自定义 DateTime,并且在 {3} 当前时间中,始终使用 UTC 时区。

我必须如何替换这些?这是代码,其中 "??" 是我需要计算的字符串:

string query = String.Format(AddExchangeQuery, "EUR", "USD", "??", "??", "3.2");
NpgsqlCommand command = new NpgsqlCommand(query, connection);
command.ExecuteScalar();

您可以将 {2} 的 C# 时间戳格式化为 PG 可以正确解释的格式。请参阅此处以插入带时区的时间戳:https://www.postgresql.org/docs/current/static/datatype-datetime.html#DATATYPE-TIMEZONE-TABLE

至于{3},因为您希望它是当前时间,您可以通过设置默认值来更改table来为您处理它:

CREATE TABLE rates
(
  source character varying(5) NOT NULL,
  target character varying(5) NOT NULL,
  "from" timestamp with time zone NOT NULL,
  "to" timestamp with time zone DEFAULT current_timestamp,
  exchange_rate numeric(10,10) NOT NULL,
)

那么你根本不需要提供它,它总是被设置为插入记录的时间(尽管要注意 current_timestampclock_timestamp() 之间的区别,并相应地选择)。