2015-10-07 101 views
0

即時通訊困惑如何做到這一點,因爲我是相當新的c#訪問sql服務器。 我想用時間在startTime和EndTime之間的條件查詢表格測驗。然而,當我嘗試添加時間參數,它說我有一個空引用異常。System.NullReferenceException添加日期時間SQL參數

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<[email protected] and EndTime>[email protected] and Subject_ID = @subject", con); 


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

'SqlCommand的COM = new SqlCommand(「Select * from quiz where StartTime <= @ time and EndTime> = @ time and Subject_ID = @subject」,con);'而不是'SqlCommand com; ' – fubo

回答

0

com未分配,com爲空。首先,您將參數添加到COM,然後你就COM =新的SqlCommand

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

它只是必須做其他明智的:地方

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

之前

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

謝謝!我現在意識到了。由於試圖解決以前的錯誤,並且必須改變其位置,我的代碼混亂了。這真是一個愚蠢的錯誤。 –

+0

不客氣!這就是程序員經常犯的那些小錯誤:-)很高興它現在已經修復:-) –