如何计算每行foreach double值以计算为SINGLE值?

时间:2014-02-08 14:23:00

标签: c# winforms loops foreach logic

现在我的代码背后有这个逻辑:

INSERT INTO PAYMENT (amount, appointmentID) VALUES
(@amount1, @app1),
(@amount2, @app2),
(@amount3, @app3),
...

假设@ amount1为10,@ amount2为15,@ amount3为20

如何计算amount1,amount2,amount 3等的TOTAL值,并以这种方式将其作为总值45提交到数据库中:(@ amount1,@ app1)?我该如何处理这种逻辑?

这就是我的按钮点击代码:

string cMedication = string.Empty;
string cQuantity = string.Empty;
string cAppointment = string.Empty;
foreach (DataGridViewRow row in this.dataPrescription.Rows)
{
    cMedication = row.Cells[0].Value.ToString();
    cQuantity = row.Cells[1].Value.ToString();
    cAppointment = txtAppointmentID.Text;

    if (cAppointment == "NO APPOINTMENT HAS BEEN MADE")
    {
        MessageBox.Show("Please make an appointment first at the Nurse counter", "WARNING");
    }
    else
    {
        this.calculateTotal(cMedication, cQuantity, cAppointment);
    }
}

这是我的calculateTotal函数:

private void calculateTotal(string cMedication, string cQuantity, string cAppointment)
{
    string strConnectionString = ConfigurationManager.ConnectionStrings["HConnection"].ConnectionString;
    SqlConnection con = new SqlConnection(strConnectionString);

    string insertPayment = "INSERT INTO PAYMENT (amount, appointmentID) " +
        "VALUES (@insertAmount, @insertAppointment)";

    using (SqlConnection connection = new SqlConnection(strConnectionString))
    {
        using (SqlCommand cmdPayment = new SqlCommand(insertPayment, connection))
        {
            string strPrice = "SELECT medicationPrice FROM MEDICATION WHERE medicationName= @getName";
            SqlCommand cmdPrice = new SqlCommand(strPrice, con);
            cmdPrice.Parameters.AddWithValue("@getName", cMedication);

            con.Open();
            SqlDataReader readPrice = cmdPrice.ExecuteReader();
            if (readPrice.Read())
            {
                string getPrice = readPrice["medicationPrice"].ToString();
                double doublePrice = Convert.ToDouble(getPrice);
                double doubleQuantity = Convert.ToDouble(cQuantity);

                double result = doublePrice * doubleQuantity;

                string answer = result.ToString();
                cmdPayment.Parameters.AddWithValue("@insertAmount", answer);
            }

            readPrice.Close();
            con.Close();

            cmdPayment.Parameters.AddWithValue("@insertAppointment", txtAppointmentID.Text);

            connection.Open();
            cmdPayment.ExecuteNonQuery();
            connection.Close();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您需要避免过多的往返数据库。循环中的一对select-insert语句不被视为最佳实践。

我尝试使用INSERT INTO SELECT语句。类似的东西:

INSERT INTO PAYMENT (amount, appointmentID) 
SELECT price * quantity, appointmentID FROM MEDICATION
INNER JOIN APPOINTMENT
ON "whatever_matches_medications_and_appointments"