在循环中重用 C# SQLParameter
本文关键字:SQLParameter 循环 | 更新日期: 2023-09-27 18:36:05
我创建一个命令(stord proc)并添加两个参数。然后,我想遍历一个数组,并简单地在每个循环上重新分配两个参数并执行查询。我最初使用 cmd.Parameters.AddWithValue(name,value)
INSIDE 循环,这表明我的参数数量每次循环迭代都会增加 2 个(它有效 - 但仍然不是好的设计)。但是,我想以正确的方式做到这一点。
我还尝试清除每个循环迭代结束时的参数列表并在循环中重新添加参数 - 但这根本不起作用。没有任何东西插入到数据库中
如何将两个参数分配给循环外部的命令,然后在循环内为两个参数分配新值并执行?
//Set command text
//Create both parameters
//loop
// assign parameter 1
// assign parameter 2
// execute command
//end loop
您可以简单地使用参数的索引来重新分配值。
SqlCommand cmd = new SqlCommand("Select * from tbl where id = @id AND otherID = @other");
cmd.Parameters.Add("@id", SqlDbType.Int);
cmd.Parameters.Add("@other", SqlDbType.Int);
for (int i = 0; i < 10; i++)
{
cmd.Parameters["@id"].Value = i;
cmd.Parameters["@other"].Value = i * 10;
cmd.Execute();
}
像这样:
//Set command text
//Create both parameters
command.Parameters.Add("@ID", SqlDbType.Int);
command.Parameters.Add("@Age", SqlDbType.Int);
//loop
// assign parameter 1
// assign parameter 2
command.Parameters["@ID"].Value = customerIDs[i];
command.Parameters["@Age"].Value = customerAges[i];
// execute command
//end loop