转换时的日期时间问题。参数化查询不接受日期时间值

时间:2013-05-23 13:02:35

标签: c# sql datetime parameterized-query

我有这个函数ExecuteSqlParameterizedQuery,下面是我的查询:

Queryobj.ExecuteSqlParameterizedQuery(String.Format("INSERT INTO tbladd(ID,MyDateTime,Birthday)values({0},@dta, @dtb)", m_Id, MyDateTime.ToString(), MyBirthday.ToString());
  1. MyDateTime属于DateTime数据类型。
  2. MyBirthday属于DateTime数据类型。
  3. 这是我的功能:

    readonly SqlConnection con = new SqlConnection(PC_Software.Properties.Settings.Default.DbConnectionString);
    
        public void ExecuteSqlParameterizedQuery(string SQL, string measdt, string dob)
        {
            try
            {
                using (var cmd = new SqlCommand())
                {
                    con.Open();
                    cmd.Connection = con;
                    cmd.Parameters.Clear();  
                    cmd.Parameters.AddWithValue("@dta", measdt);
                    if(dob != "0DATA#")
                    {
                        cmd.Parameters.AddWithValue("@dtb", dob);
                    }
                    cmd.CommandText = SQL;
                    cmd.ExecuteNonQuery();
                }
                con.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    

    这显示了这个特殊错误:the conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value. the statement has been terminated.

    我试图找到问题但无法理解我是如何更改我的代码以纠正问题。

    修改

    此外,我将此作为我的日期时间界面:

    public interface enn
    {
        DateTime MyDateTime
        {
            get;
            set;
        }
    }
    

    日期时间声明是这样的:

        DateTime? MyBirthday
        {
            get;
            set;
        }
    

2 个答案:

答案 0 :(得分:1)

MyBirthday参数传递给方法时,您将其转换为字符串:

MyBirthday.ToString()

您应将其保留为DateTime - 与MyDateTime

相同

您显然需要更改方法签名以接受这些值

答案 1 :(得分:0)

尝试使用:

  

MyDateTime.Date

     

MyBirthday.Date

Queryobj.ExecuteSqlParameterizedQuery(String.Format("INSERT INTO tbladd(ID,MyDateTime,Birthday)values({0},@dta, @dtb)", m_Id, MyDateTime.Date, MyBirthday.Date);