2011-07-17 21 views
0

我有下面的代碼:問題在SQL查詢字符串在cmd

private int bla(out int itemsMin, out int purchase) 
{ 
    string ID = (Request.QueryString["Ttrsid"] ?? "0").ToString(); 
    { 

     SqlConnection connection = new SqlConnection("Data Source=*****;Initial Catalog=****;User ID=****;Password=*****;Integrated Security=False;"); 
     string commandtext = "SELECT Min FROM myItems WHERE [email protected]"; 
     SqlCommand command = new SqlCommand(commandtext, connection); 

     connection.Open(); 
     command.Parameters.AddWithValue("@ID", ID); //Adds the ID we got before to the SQL command 
     itemsMin = (int)command.ExecuteScalar(); 
     string commandtext2 = "SELECT COUNT (*) FROM purchase"; 
     SqlCommand command2 = new SqlCommand(commandtext2, connection); 
     purchase = (int)command2.ExecuteScalar(); 
    } 



    return 0; 



} 

的代碼是,我使用兩個標籤 - 一個拿到最低數量(itemsMin),另一種是對的計數此次購買。

我正在使用查詢字符串來獲取用戶在他身上觀看的itemid的值..(從地址欄(例如:items.aspx?Ttrsid = 5,所以我想查看最小數量Ttrsid = 5)

一切正常,當我在Ttrsid = 1時,Ttrsid = 2 - 我得到我想要的,但是當我被輸入到Ttrsid = 3等等 - 這是給我的錯誤:

System.NullReferenceException

到該行:

itemsMin = (int)command.ExecuteScalar();

..並且它不是null ..該項目具有所有必需的字段,如Ttrsid = 2 ....所以這裏有什麼錯誤?

下一個代碼是使用上述命令的:

 int i, p; // variable need not be initialized 
    Console.WriteLine(bla(out i, out p)); 
    if (i < p) 
    { 
     haha.Visible = true; 

    } 
    else 
    { 
     haha2.Visible = true; 
    } 
    Console.WriteLine(i); 
    Console.WriteLine(p); 

I = itemsMin,P =購買。

+0

你確定,你對ID = 3或4,5的數據? –

+0

是的,我確定。我在SQL服務器上查詢時觸發它 – Oshrib

+0

你能告訴我們你在SQL服務器上測試過的相同查詢嗎? –

回答

0

我猜數據庫中沒有匹配的行,所以沒有行返回。理智 - 從ExecuteScalar檢查結果 - 特別是在轉換爲int之前檢查它是否爲null。也可能該列包含空值,但也許我希望DBNull.Value。

另外 - 在這裏的所有IDisposable對象上使用using;特別是連接和命令。

+0

謝謝。我試圖在查詢中的SQL服務器上 - 我得到了正確的結果。但在頁面上仍然是問題。 – Oshrib

+0

@抱歉我 - 在代碼***中檢查***無論如何。這裏有一個想法 - 在數據庫是一個字符串或整數的ID? –

+0

我編輯了更多細節的問題。 – Oshrib

0

我認爲下面粘貼的變量是int型變量

purchase = (int) 

因此,你可能不能爲null值轉換爲整數所以請嘗試更改SQL命令,如下

SELECT isNull(COUNT (*),0) FROM purchase 

@Marc我真的很抱歉

難道你不想在min語句旁邊指定一個列名嗎?正如下面

SELECT Min(columnName) FROM myItems WHERE [email protected] ? 
+0

有問題的行是itemsMin,而不是購買 –

+0

另外,你爲什麼要發短信,謝謝 –

+0

最後,COUNT會返回0,而不是null –