[英]Insert timestamp with timezone in query from C#
我将下表放入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,
)
我有一个带有一些占位符的文本查询,用于在该表中插入一行:
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}
,由于您希望它是当前时间,因此可以通过设置默认值来更改表以为您处理它:
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_timestamp
和clock_timestamp()
之间的差异,并进行相应选择)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.