System.IndexOutOfRangeException:索引超出数组范围

发布于 2024-12-23 18:48:08 字数 1485 浏览 0 评论 0原文

我正在开发一个 ATM 软件作为家庭作业,我想知道今天处理的交易总量,为此我编写了以下代码,

 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:索引超出范围数组的一部分,尽管在数据库中可以通过在查询窗口中运行相同的查询来获取多个记录。但我不知道如何通过编码来获得它。

请帮我。

问候

I am developing an ATM Software as a home work in which i want to know the total amount of transaction which is processed today, for this purpose I am writting the following code

 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;
            }
        }

But i am getting the exception System.IndexOutOfRangeException: Index was outside the bounds of the array, although in database more than one records are available which are getting by running the same query in query window. But I don't know how to get it through coding.

Please help me.

Regards

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

来日方长 2024-12-30 18:48:08

像这样改变 while 。

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

那里不需要 i

Change the while like this.

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

There is no need of an i there

北笙凉宸 2024-12-30 18:48:08

在我看来,那是因为您试图阅读太多专栏。

           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;

Thats because you're trying to read too many columns IMO.

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

                i++;

            }

Who said there are more columns than rows?
It seems like you're trying to sum a single column.

You're wasting time by selecting all rows. if you're looking for the SUM, use SUM(COLUMN1) instead

                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;
悲歌长辞 2024-12-30 18:48:08

我认为问题出在这一行为

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

什么要增加 i for?您不需要增加 i

i 代表这里的列索引。您应该从同一列读取,因此不需要增加 i

此外,建议使用列名称而不是索引检索值

I think problem is in this line

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

Why are incrementing i for? you don't need to increment i

i represents the column index here. You are suppose to read from same column so you don't need to increment i.

Also it is a recommended practise to retrieve value using column name instead of index

乖乖兔^ω^ 2024-12-30 18:48:08

当您只需要获取一个值时,请使用 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 注入攻击,请考虑使用参数化命令。您可以在 SqlCommand 的 MSDN 文档

When you should get only one value, use the SqlCommand.ExecuteScalar, which returns a single value.

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();   

To avoid SQL injection attacks, consider to use parameterized commands. You can find information about Execute.Scalar and Parametrized command example in the MSDN Documentation for SqlCommand.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文