dbncourt
dbncourt

Reputation: 580

PostgreSQL date C# DateTime

I'm using this query to insert into a table a date:

DateTime dt = DateTime.Now;
String query = "Insert into \"Table1\" (\"tableDate\") values (:date1)";
NpgsqlConnection conn = new NpgsqlConnection(conex.getConnection());
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand(query, conn);
NpgsqlParameter param = new NpgsqlParameter(":date1",NpgsqlTypes.NpgsqlDbType.Date);
param.Value = dt.ToShortDateString();
cmd.Parameters.Add(param); // <----------Here i get the error
cmd.ExecuteNonQuery();
conn.Close();

And this is how I am inserting in the table any other value and it works! So there must be an error in the date format or something, but I can't find the answer.

Upvotes: 5

Views: 19588

Answers (1)

Sergii Kudriavtsev
Sergii Kudriavtsev

Reputation: 10532

Don't do

param.Value = dt.ToShortDateString(); 

leave just

param.Value = dt; 

You're trying to insert a string into DateTime field - sure PostgreSQL will complain.

use NpgsqlTypes.NpgsqlDbType.Timestamp if you want to avoid losing the time information

Upvotes: 10

Related Questions