0

im confused on how to do this as I am quite new to accessing sql server by c#. I want to query table quiz with conditions where time is in between startTime and EndTime. however, when i try to add the time parameter, it says I have a null reference exception.

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();
  • `SqlCommand com = new SqlCommand("Select * from quiz where StartTime<=@time and EndTime>=@time and Subject_ID = @subject", con);` instead of `SqlCommand com; ` – fubo Oct 07 '15 at 12:06

1 Answers1

0

Com is not assigned, com is null. You first add the parameter to the com and then you do 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)

It simply has to be done other wise: place

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

Before

com.Parameters.Add(time); //<-- com = null
Joshua Bakker
  • 2,288
  • 3
  • 30
  • 63
  • 1
    thank you! I realize that now. I had my code jumbled due to trying to fix a previous error and must have shuffled their placement. It's a silly mistake, really. – Franchette Camoro Oct 07 '15 at 12:24
  • You're welcome! It's those small mistakes that programmers make pretty often :-) Glad it's fixed now :-) – Joshua Bakker Oct 07 '15 at 12:25