Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 执行参数化查询后,参数是否将从ParameterCollection中删除?_C#_Sql Injection_Sql Parametrized Query - Fatal编程技术网

C# 执行参数化查询后,参数是否将从ParameterCollection中删除?

C# 执行参数化查询后,参数是否将从ParameterCollection中删除?,c#,sql-injection,sql-parametrized-query,C#,Sql Injection,Sql Parametrized Query,我的方法中有许多查询。根据条件,执行特定的查询。每个查询使用相同的参数 例如: public static void Method(param1, param2, param3) { .... cmd.CommandType = CommandType.Text; if(Condition1) { cmd.CommandText = "select * from Table1 where id=@id" cmd.Parameters.AddWith

我的方法中有许多查询。根据条件,执行特定的查询。每个查询使用相同的参数

例如:

public static void Method(param1, param2, param3)
{
   ....
   cmd.CommandType = CommandType.Text;
   if(Condition1)
   {
      cmd.CommandText = "select * from Table1 where id=@id"
      cmd.Parameters.AddWithValue("@id", param1);
      cmd.ExecuteNonQuery();

      foreach(int i in IntegerList)
      {
          ....
          cmd.CommandText = "insert into Table2(id,type,model) values(@id,@type,@model)
          cmd.Parameters.AddWithValue("@id", param1);
          cmd.ExecuteNonQuery();
          ....       
      }
   }
   else
   {
      cmd.CommandText="select * from Table3 where id = @id"
      cmd.Parameters.AddWithValue("@id", param1);   
      SqlDataAdapter da = new SqlDataAdapter();
      da.SelectCommand = cmd;
      DataSet ds = new DataSet();
      da.Fill(ds);
      cmd.Dispose();
      da.Dispose();
      ....
   }
   cmd.CommandText = "delete from Table3 where id = @id and model=@model..."
   ....
}


我的问题是,如果每次我需要执行不同的查询时都不断添加参数
@id
,或者我的参数在执行查询后会被删除,那么我会有错误吗?

您应该添加一个类型为的参数,然后在需要时设置其值。这将确保类型始终正确

这就是说,参数在执行后不会被删除,而且与前面的
Add
不同,如果密钥已经存在,
AddWithValue
似乎不会引发异常。因此,您应该能够再次添加参数


当然,如果值相同,并且只有查询发生了更改,则无需再次添加

首先使用所有参数准备命令对象,然后在循环中指定新值

command.Parameters.Add("@id", SqlDbType.Int);
foreach (...) {
    command.Parameters["@id"].Value = param1; 
    command.ExecuteNonQuery();
}