我正在使用此查询将日期插入表中:
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();
这就是我在表中插入任何其他值的方式,它起作用了!所以一定是日期格式有什么错误,但是我找不到答案。
最佳答案
不要做
param.Value = dt.ToShortDateString();
离开
param.Value = dt;
您正在尝试将字符串插入 DateTime 字段 - PostgreSQL 肯定会报错。
如果你想避免丢失时间信息,请使用 NpgsqlTypes.NpgsqlDbType.Timestamp
关于c# - PostgreSQL 日期 C# DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9476476/