无法从c#dapper代码向Nexus数据库插入日期时间作为空值

时间:2018-06-04 14:53:57

标签: c# nexusdb

使用dapper类将nexus数据库中的DateTime值作为null插入到nexus数据库中时出现以下问题。

public const string SqlQuery = @"INSERT INTO Test(test1, test2, test3, 
Date1,Date2))
                                                       Values(?test1?,? 
test2?,?date1?,?date2?)";

 public void InsertTest(string test1,string test2, DateTime? date1,DateTime? 
date2)
{
var params= new DynamicParameters(
            new
            {
test1= "",
test2 ="",
Date1 = cDate.HasValue ? cDate.Value.Date : (DateTime?)null,
Date2 = cDate1.HasValue ? cDate2.Value.Date : (DateTime?)null,

}
ExecConn(SqlQuery , params);
}

错误[HY000]查询返回错误(ODBC状态:HY000)

错误: 日期编码的参数无效

查询: 吨60000; INSERT INTO Test(test1,test2,test3,Date1,Date2)值(:Param1,:Param2,:Param3,:Param4,:Param5)

2 个答案:

答案 0 :(得分:2)

尝试使用DateTime.MinValue而不是(DateTime?)null

public void InsertTest(string test1,string test2, DateTime? date1,DateTime? 
date2)
{
 var params= new DynamicParameters(
        new
        {enter code here
 test1= "",
 test2 ="",`enter code here`
 Date1 = cDate.HasValue ? cDate.Value.Date :   DateTime.MinValue.Date,
 Date2 = cDate1.HasValue ? cDate2.Value.Date :   DateTime.MinValue.Date,

 }
 ExecConn(SqlQuery , params);
 }

答案 1 :(得分:0)

通常在db层(对于oracle和MSSQL),我们必须做这样的事情

(PS这是从我的代码中获取的,我还必须允许在excel中使用类似于31/2/2018的半功能类型的事实!)

如果实际为null或无效,则将其转换为DBNull.Value。哪个应该有用。

       private object dtfix(object o)
        {
            if (!(o is DateTime))
            {
                return null;
            }
            else
            {
                try
                {
                    DateTime x = (DateTime)o;
                    x.AddDays(1);
                }
                catch
                {
                    return null;
                }
                return o;
            }
        }

param = new SqlParameter("duedate", SqlDbType.Date);
param.Value = dtfix(myparm) ?? DBNull.Value;