在按钮单击时多次动态地将数据添加到数据库

时间:2016-03-12 19:19:48

标签: c# sql asp.net

我可以在日期值更改的情况下将两个不同的行同时添加到数据库中。代码是多余的,看起来不太好。不知道我怎么能让它变得动态。

SqlCommand cmd = new SqlCommand("insert into Incomings (AspNetUsersId,IncType,IncDate,IncCost,IncFrequency) values (@AspNetUsersId, @IncType, @IncDate, @IncCost, @IncFrequency)");
SqlCommand cmd2 = new SqlCommand("insert into Incomings (AspNetUsersId,IncType,IncDate,IncCost,IncFrequency) values (@AspNetUsersId, @IncType, @IncDate, @IncCost, @IncFrequency)");

if (frequencyIncoming.Text == "Weekly")
    {
       DateTime newDate = DateTime.ParseExact(lblCalendar.Text, "dd/MM/yyyy", null);


        cmd.Parameters.AddWithValue("@AspNetUsersId", userId);
        cmd.Parameters.AddWithValue("@IncType", typeIncoming.Text);
        cmd.Parameters.AddWithValue("@IncDate", lblCalendar.Text);
        cmd.Parameters.AddWithValue("@IncCost", costIncoming.Text);
        cmd.Parameters.AddWithValue("@IncFrequency", frequencyIncoming.Text);

        cmd2.Parameters.AddWithValue("@AspNetUsersId", userId);
        cmd2.Parameters.AddWithValue("@IncType", typeIncoming.Text);
        cmd2.Parameters.AddWithValue("@IncDate", newDate.AddDays(7).ToString(@"dd\/MM\/yyyy"));
        cmd2.Parameters.AddWithValue("@IncCost", costIncoming.Text);
        cmd2.Parameters.AddWithValue("@IncFrequency", frequencyIncoming.Text);
    }

loadDatabase(cmd);
loadDatabase(cmd2);

Response.Redirect(Request.Url.AbsoluteUri);

目前它的工作原理虽然代码不是很好而且是多余的。这是一个开始。唯一的问题是如果例如我选择每日频率,并希望将其添加14天,我将不得不做14种不同的选择语句,这是可怕的做法。不知道怎么整理这个。提前致谢

1 个答案:

答案 0 :(得分:1)

你可以简单地使用for循环迭代14次,并在每个循环中创建新的sql cmd并执行它。像这样......

var connection = new SqlConnection("<your connection string here>");
connection.Open();
// do what ever else you want to do

DateTime newDate = DateTime.ParseExact(lblCalendar.Text, "dd/MM/yyyy", null);


try {
    for (var i = 0; i < 14; i++) {
         SqlCommand cmd = new SqlCommand("insert into Incomings (AspNetUsersId,IncType,IncDate,IncCost,IncFrequency) values (@AspNetUsersId, @IncType, @IncDate, @IncCost, @IncFrequency)", connection);

         cmd.Parameters.AddWithValue("@AspNetUsersId", userId);
         cmd.Parameters.AddWithValue("@IncType", typeIncoming.Text);
         cmd.Parameters.AddWithValue("@IncDate", lblCalendar.Text);
         cmd.Parameters.AddWithValue("@IncCost", newDate.AddDays(i).ToString(@"dd/MM/yyyy"));
         cmd.Parameters.AddWithValue("@IncFrequency", frequencyIncoming.Text);

         cmd.ExecuteNonQuery();
    }
} finally {
    connection.Close();
}