2012-05-13 54 views
0

當我在我的數據庫上執行此命令時,有時會收到result = null。我想在這種情況下輸入「其他」部分,但我收到從數據庫中接收到NULL時出錯

mscorlib.dll中發生未處理的異常類型'System.FormatException'。 附加信息:輸入字符串格式不正確。

DB database = new DB(); 
      int reservedSeats = 0; 
      using (database.sqlConnection) 
      { 
       database.sqlConnection.Open(); 
       string command = "select SUM(nrLocuri) as result from Rezervari where idRand = @idRand and [email protected]"; 
       using (SqlCommand cmd = new SqlCommand(command, database.sqlConnection)) 
       { 
        cmd.Parameters.Add("@idRand", SqlDbType.Int).Value = idRand; 
        cmd.Parameters.Add("@idShow", SqlDbType.Int).Value = idShow; 
        using (SqlDataReader dr = cmd.ExecuteReader()) 
        { 
         if (dr.Read()) 
          if (dr["result"].ToString() != null) 
           reservedSeats = Convert.ToInt32(dr["result"].ToString()); 
          else 
           return totalSeats; 
        } 
       } 
      } 
      return totalSeats-reservedSeats; 
+0

您需要在異常處理讀了。 –

+0

列結果的數據類型是什麼? –

回答

6

相反的:

if (dr["result"].ToString() != null) 

務必:

if (dr["result"] != DbNull.Value) 

dr["result"]返回數據庫null,其價值DbNull.Value - 當你嘗試調用Convert.ToInt32該值,你會得到一個格式異常。

+0

'DbNull'等同於'null'嗎? –

+0

@ ta.speot.is - 不,不,它不會... – Oded

1

如果你想SUM()在沒有發現記錄的事件中返回0.00,將其替換爲:

COALESCE(SUM(...), 0.00) 

COALESCE將返回傳遞給它的第一個非空值。

1

嘗試isnull

string command = "select isnull(SUM(nrLocuri),0.00)as result from Rezervari where idRand = @idRand and [email protected]"; 
+0

如果他根本沒有行,這將不起作用 – YvesR

2

嘗試:

if(!dr.IsDBNull(i)){ //replace i with the column id 

    //get the data 

} 
+1

您不應該依賴數據訪問層中的序號 - 列位置可能會更改。 – Oded