简体   繁体   English

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

[英]Insert timestamp with timezone in query from C#

I've the following table into my PostgreSQL database: 我将下表放入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,
)

I've a text query with some placeholders for inserting a row into this table: 我有一个带有一些占位符的文本查询,用于在该表中插入一行:

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

I don't know how I must replace placeholders {2} and {3} in order to give the correct timestamp with timezone. 我不知道如何替换占位符{2}{3}才能为时区提供正确的时间戳。

I need to put in {2} a custom DateTime with UTC timezone, that I specify, and in {3} the current time, always with UTC timezone. 我需要在{2}放入我指定的带有UTC时区的自定义DateTime ,并在{3}放入当前时间,并始终使用UTC时区。

How I must replace these? 我该如何替换这些? Here's the code, where "??" 这是代码,其中"??" are strings that I need to calculate: 是我需要计算的字符串:

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

You could format the timestamp in C# for {2} to a format that PG will interpret correctly. 您可以将{2} C#中的时间戳格式化为PG可以正确解释的格式。 See here for inserting timestamps with time zones: https://www.postgresql.org/docs/current/static/datatype-datetime.html#DATATYPE-TIMEZONE-TABLE 请参阅此处以插入带有时区的时间戳: https : //www.postgresql.org/docs/current/static/datatype-datetime.html#DATATYPE-TIMEZONE-TABLE

As for {3} , since you want it to be the current time, you could change the table to handle it for you by setting a default: 至于{3} ,由于您希望它是当前时间,因此可以通过设置默认值来更改表以为您处理它:

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,
)

Then you don't need to supply it at all, and it will always be set to the time the record was inserted (though be aware of the difference between current_timestamp and clock_timestamp() , and choose accordingly). 然后,您根本不需要提供它,并且它将始终设置为插入记录的时间(尽管请注意current_timestampclock_timestamp()之间的差异,并进行相应选择)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM