2012-01-01 158 views
4

我正在開發一種ATM軟件作爲家庭作業,其中我想知道今天處理的事務總量,爲此,我正在寫下面的代碼System.IndexOutOfRangeException:索引超出數組範圍

public decimal getDayTransaction(int accountid, string date, string transactiontype) 
     { 
      decimal totalamount = 0; 
      int i = 0; 
      string connectionString = 
        "Persist Security Info=False;User ID=sa; Password=123;Initial Catalog=ATMSoftware;Server=Bilal-PC"; 
      try 
      { 
       using (SqlConnection connection = 
           new SqlConnection(connectionString)) 
       { 


        SqlCommand command = new SqlCommand(
         "Select Amount From [Transaction] where AccountID = " 
         + accountid + " AND CurrDate ='" + date 
         + "' AND TransactionType = '" 
         + transactiontype + "';", connection); 

        connection.Open(); 
        SqlDataReader dr = command.ExecuteReader(); 
        while (dr.Read()) 
        { 
         totalamount += Convert.ToDecimal(dr.GetString(i)); 

         i++; 

        } 
        return totalamount; 
       } 


      } 
      catch (Exception e) 
      { 

       return -1; 
      } 
     } 

但我得到異常System.IndexOutOfRangeException:索引是該數組的範圍之外,但在數據庫中的多個記錄,它們有越來越運行在查詢窗口相同的查詢。但我不知道如何通過編碼來獲得它。

請幫幫我。

Regards

+0

您應該使用[參數化SQL](http://msdn.microsoft.com/zh-cn/library/system.data.sqlclient.sqlparameter.aspx)。 – 2012-01-01 12:21:47

回答

3

那是因爲你想讀取太多列IMO。

  while (dr.Read()) 
      { 
       totalamount += Convert.ToDecimal(dr.GetString(i)); 

       i++; 

      } 

誰說有更多的列比行? 這似乎是你試圖總結一列。

通過選擇所有行來浪費時間。如果您正在尋找SUM,請使用SUM(COLUMN1)代替

   SqlCommand command = new SqlCommand("Select SUM(Amount) as sAmount From [Transaction] where AccountID = " + accountid + " AND CurrDate ='" + date+ "' AND TransactionType = '" + transactiontype + "';", connection); 

       connection.Open(); 
       SqlDataReader dr = command.ExecuteReader(); 
       while (dr.Read()) 
       { 
        totalamount += Convert.ToDecimal(dr.GetString(0)); 
        break; // Only read once, since it returns only 1 line. 

       } 
       return totalamount; 
4

改變這樣的情況。

while (dr.Read()) 
{ 
    totalamount += Convert.ToDecimal(dr.GetString(0)); 
} 

沒有必要的i

2

我覺得問題是在這條線

totalamount += Convert.ToDecimal(dr.GetString(i)); 
    i++; 

爲什麼對被遞增i?你不需要增加i

i代表column index這裏。您應該閱讀同一列,因此您無需增加i

而且它是一個推薦的做法使用column name代替index

0

檢索值。當你應該只有一個值,使用SqlCommand.ExecuteScalar,它返回一個值。

SqlCommand command = new SqlCommand("Select SUM(Amount) as TotalAmount From [Transaction] where AccountID = " + accountid + " AND CurrDate ='" + date + "' AND TransactionType = '" + transactiontype + "';", connection); 

connection.Open(); 
decimal totalAmount = (decimal)command.ExecuteScalar(); 

要避免SQL注入攻擊,請考慮使用參數化命令。您可以在MSDN Documentation for SqlCommand中找到有關Execute.Scalar和Parametrized命令示例的信息。