If you have to add the parameter and then delete to add again because in your case it is an item interaction and you can still change the CommandText
out of the foreach
, you only need to know this once, example:
cmd.CommandText = "INSERT INTO MinhaTabela (Coluna_A, Coluna_B, Coluna_C) " +
"VALUES (@Val_A, @Val_B, @Val_C)";
foreach (var item in pedidos)
{
cmd.Parameters.AddWithValue("@Val_A", item.AttributoA);
cmd.Parameters.AddWithValue("@Val_B", item.AttributoB);
cmd.Parameters.AddWithValue("@Val_C", item.AttributoC);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear(); // adicione essa linha para limpar os parametros existentes.
}
has another way that would use the same parameter created and change its value, but, your code would have to be checking the existence or not of the created parameter, I believe it is more practical to clear the parameters and add again, but, will a example of that also:
cmd.CommandText = "INSERT INTO MinhaTabela (Coluna_A, Coluna_B, Coluna_C) " +
"VALUES (@Val_A, @Val_B, @Val_C)";
foreach (var item in pedidos)
{
if (command.Parameters.Contains("@Val_A"))
{
command.Parameters["@Val_A"].Value = item.AttributoA;
}
else
{
command.Parameters.AddWithValue("@Val_A", item.AttributoA);
}
if (command.Parameters.Contains("@Val_B"))
{
command.Parameters["@Val_B"].Value = item.AttributoB;
}
else
{
command.Parameters.AddWithValue("@Val_B", item.AttributoB);
}
if (command.Parameters.Contains("@Val_C"))
{
command.Parameters["@Val_C"].Value = item.AttributoC;
}
else
{
command.Parameters.AddWithValue("@Val_C", item.AttributoC);
}
}
References
Man, it worked perfectly. Thank you.
– Ricardo Alves
If the answer to your question is accepted!
– novic
I’ll accept yes, I haven’t done it yet because the S.O asks to wait a few minutes to accept.
– Ricardo Alves