c# - PostgreSQL 日期 C# DateTime

标签 c# postgresql datetime insert

我正在使用此查询将日期插入表中:

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/

相关文章:

sql - postgres 中的 connect_by_root 等价物

javascript setHours 日期设置为上一个日期

c# - 从 Epoch C# 开始的天数中获取日期字符串

c# - 设置日期时间格式 - C#

c# - Entity Framework 核心包含过滤器

c# - 本地游戏对象变量不能使用 switch 方法 (Unity)

c# - DataGrid 的自定义列模板

ruby-on-rails - Rails 唯一列有重复项

ruby-on-rails - 将 update_attributes 与列类型的数组一起使用

c# - 不使用 Microsoft.AspNet.Identity.EntityFramework 的自定义 Asp.net mvc 5 身份验证