Jepessen
Jepessen

Reputation: 12435

Insert timestamp with timezone in query from C#

I've the following table into my PostgreSQL database:

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.

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.

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();

Upvotes: 0

Views: 4111

Answers (1)

404
404

Reputation: 8572

You could format the timestamp in C# for {2} to a format that PG will interpret correctly. See here for inserting timestamps with time zones: 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:

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

Upvotes: 1

Related Questions