System.NullReferenceException添加DateTime SQL参数

时间:2015-10-07 12:04:02

标签: c# sql

我很困惑如何做到这一点,因为我很陌生,通过c#访问sql服务器。 我想查询表测验,其中时间介于startTime和EndTime之间。但是,当我尝试添加时间参数时,它表示我有一个空引用异常。

DateTime date = DateTime.Now;

    SqlConnection con = new SqlConnection("Data Source=.\\SQLSERVER;Initial Catalog=quizMaker;Integrated Security=True");
    SqlCommand com;     

subjects = "Subject-3";



        con.Open();
        SqlParameter time = new SqlParameter("@time", SqlDbType.DateTime);
        time.Value = date;
        com.Parameters.Add(time); //error pops up here
        SqlParameter subjected = new SqlParameter("@subject", SqlDbType.VarChar, 20);
        subjected.Value = subjects;
        com = new SqlCommand("Select * from quiz where StartTime<=@time and EndTime>=@time and Subject_ID = @subject", con);


        com.ExecuteNonQuery();
        con.Close();

1 个答案:

答案 0 :(得分:0)

未分配Com,com为null。首先将参数添加到com,然后执行com = new SqlCommand

com.Parameters.Add(time); //<-- com = null
com = new SqlCommand("Select * from quiz where StartTime<=@time and EndTime>=@time and Subject_ID = @subject", con); //<-- com has a value (!= null)

只需要做其他明智的事情:放置

com = new SqlCommand("Select * from quiz where StartTime<=@time and EndTime>=@time and Subject_ID = @subject", con); //<-- com has a value (!= null)

com.Parameters.Add(time); //<-- com = null