如何通过带参数的DbCommand将System.Datetime对象插入SqlServer

本文关键字:Datetime System 对象 插入 SqlServer DbCommand 何通过 参数 | 更新日期: 2023-09-27 18:28:49

我试着做了几个小时。

            Database db = DBUtil.GetInstance().GetDataBase();
            DbCommand cmd = db.GetSqlStringCommand(@"INSERT INTO [XXX] (
            ...
                                                                  ,[FirstDate]
            ...
            ) VALUES ('@FirstDate',...");
            db.AddInParameter(cmd, "@FirstDate", DbType.Date, DateTime.Now );

但我总是在下面得到这些异常信息。

{System.Data.SqlClient.SqlException(0x80131904):转换失败从字符串转换日期和/或时间时。

我应该为转换做些什么?或者选择另一个DbType?数据库类型日期时间2?

如何通过带参数的DbCommand将System.Datetime对象插入SqlServer

您不需要为Insert语句中的参数添加引号(值('@FirstDate')

    Database db = DBUtil.GetInstance().GetDataBase();
    DbCommand cmd = db.GetSqlStringCommand(@"INSERT INTO [XXX] (
    ...
                                                          ,[FirstDate]
    ...
    ) VALUES (@FirstDate,...");
   db.AddInParameter(cmd, "@FirstDate", DbType.DateTime, DateTime.Now );

取决于数据库中的类型是Date还是DateTime。

// full date and time
db.AddInParameter(cmd, "@FirstDate", DbType.DateTime, DateTime.Now );

// just the date portion
db.AddInParameter(cmd, "@FirstDate", DbType.Date, DateTime.Now.Date );