2015-05-18 47 views
0

我試圖查看這個,但沒有其他問題真的適合。我有一個網頁,我將展示分析。一個統計數據是用戶的總數量,我試圖在SQL數據庫中的用戶表中獲取總數的行數。我曾以爲Id是一個整數,但它似乎是varchar(128)。我將包括錯誤和代碼。謝謝!!System.IndexOutOfRangeException當試圖返回'select count(Id)'

型「System.IndexOutOfRangeException」的異常出現在System.Data.dll中,但在用戶代碼中沒有處理

public static string GetUserSum(string rConnStr) 
    { 
     string UserCount = ""; 

     using (SqlConnection conn = new SqlConnection(rConnStr)) 
     { 
      const string sqlText = @" 
SELECT COUNT(Id) 
FROM AspNetUsers 
      "; 

      using (SqlCommand cmd = new SqlCommand(sqlText, conn)) 
      { 

       conn.Open(); 

       using (SqlDataReader sdr = cmd.ExecuteReader()) 
       { 
        bool result = sdr.Read(); 
        if (result) 
        { 

         UserCount = DBUtils.GetValue<string>(sdr["Id"]); //it breaks right here 

        } 
       } 
      } 
     } 

     return UserCount; 
    } 
+1

你可以改變SDR [「ID」]以SDR [0]或添加一個別名到您的計數(同上),因爲它是有一個與返回沒有列「 ID「作爲名稱 –

回答

1

你的錯誤來自該行:

UserCount = DBUtils.GetValue<string>(sdr["Id"]); 

因爲id爲「ID」沒有字段從查詢返回。

最簡單的解決方法是:

UserCount = DBUtils.GetValue<string>(sdr[0]).Tostring(); 
3

我認爲問題是,在你的列名從SQL獲取不是你所期望的。我相信對您的代碼進行以下更改可以解決此問題。

const string sqlText = @" 
SELECT COUNT(Id) AS Id 
FROM AspNetUsers 
      ";