且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

添加具有相同名称的SQL参数

更新时间:2023-02-23 21:36:09

问题是,当您执行第一个值时,需要设置参数.然后,当您尝试执行第二个命令时,该命令存在,并且如果选中checkbox1,则已经设置了参数.

我会略有不同:
The problem is that when you execute the first one, you set the parameters. When you then try to execute the second, the command exists and has the parameters set already if checkbox1 is checked.

I would do it slightly differently:
private string insertsubscriptionquery = " INSERT INTO Subscription(SubscriptionId,TypeOfMagazine) values (@subid,@TypeOfMagazine)";
private static void InsertIfRequired(bool required, object id, object magazineType)
   {
   using (SqlCommand subcmd = new SqlCommand(insertsubscriptionquery,connstring))
      {
      if (required)
         {
         subcmd.Parameters.AddWithValue("@subid", id);
         subcmd.Parameters.AddWithValue("@TypeOfMagazine", magazineType);
         subcmd.ExecuteNonQuery();
         }
      }
   }

...
                InsertIfRequired(checkbox1.IsChecked, subscripid1, magtype1);
                InsertIfRequired(checkbox2.IsChecked, subscripid2, magtype2);
                InsertIfRequired(checkbox3.IsChecked, subscripid3, magtype3);
...


您可以用适当的类型替换object参数.


You can replace the object parameters with the appropriate type.


更改
if (checkbox2.IsChecked == true)
{
    if(subcmd.Parameters.Contains("@subid"))
    {
       subcmd.Parameters["@subid"].Value=subscripid2;
    }
    else
    {
      subcmd.Parameters.AddWithValue("@subid", subscripid2);
    }
    if(subcmd.Parameters.Contains("@TypeOfMagazine"))
    {
       subcmd.Parameters["@TypeOfMagazine"].Value=magtype2;
    }
    else
    {
      subcmd.Parameters.AddWithValue("@TypeOfMagazine", magtype2);
    }
    subcmd.ExecuteNonQuery();
}


if (checkbox3.IsChecked == true)
相同
另外,仅当checkbox3.IsChecked == true时,您才增加noofrows吗?.


Same for if (checkbox3.IsChecked == true)

Also you increment noofrows only if checkbox3.IsChecked == true, is this wanted?.