-1

我在这段代码中有错误。应该发生的情况是,如果我在数据库中有两个档位,则档位价格必须翻倍,但这段代码中发生的情况是,如果我在数据库中有两个档位,档位价格不会翻倍,如果我只有一个档位摊位价格为0。

public double GetStallPrice(int commtaxno)
{
    try
    {
        string query = "SELECT * FROM contract_details WHERE comm_tax_no = " + commtaxno;
        DatabaseString myConnectionString = new DatabaseString();
        OleDbConnection connection = new OleDbConnection();
        connection.ConnectionString = myConnectionString.connect();
        connection.Open();

        OleDbCommand command = new OleDbCommand();
        command.Connection = connection;
        command.CommandText = query;

        OleDbDataReader stallReader = command.ExecuteReader();
        stallReader.Read();

        while(stallReader.Read())
        {
            try
            {
                string query2 = "SELECT section_ID FROM specific_stall WHERE stall_no = '" + stallReader["stall_no"].ToString() + "'";
                OleDbCommand command2 = new OleDbCommand();
                command2.Connection = connection;
                command2.CommandText = query2;

                OleDbDataReader sectionReader = command2.ExecuteReader();
                sectionReader.Read();
                sectionid = Convert.ToInt32(sectionReader["section_ID"].ToString());

                try
                {
                    string query3 = "SELECT stall_price FROM stall_sections WHERE section_ID = " + sectionid;
                    OleDbCommand command3 = new OleDbCommand();
                    command3.Connection = connection;
                    command3.CommandText = query3;

                    OleDbDataReader stallPriceReader = command3.ExecuteReader();
                    stallPriceReader.Read();
                    stall_price = Convert.ToDouble(stallPriceReader["stall_price"].ToString());
                }

                catch (Exception c)
                {
                    MessageBox.Show(c.GetBaseException().ToString());
                }

            }

            catch (Exception b)
            {
                MessageBox.Show(b.GetBaseException().ToString());
            }

            sum_stall_price = sum_stall_price + stall_price;

        }

        connection.Close();
    }

    catch (Exception a)
    {
        MessageBox.Show(a.GetBaseException().ToString());
    }
    return sum_stall_price;
}
4

1 回答 1

1

我认为错误在这里:

stallReader.Read();
while(stallReader.Read())

您读取第一条记录,然后读取第二条记录,而不处理第一条记录。
您必须删除第一行并离开

while(stallReader.Read())

作为旁注,您应该尝试始终using对实现IDisposable接口的类使用语法。所以,只是一个例子:

using (OleDbConnection connection = new OleDbConnection())
{
    // All the code inside
}

通过这种方式,您可以确定对象已正确释放。

最后:不要手动编写查询,而是使用参数!
使用参数可以避免 SQL 注入以及由于数字(浮点数、双精度、货币)和日期转换而导致的许多麻烦!

于 2013-09-02T07:04:29.927 回答