gpt4 book ai didi

c# - 如何在每次迭代中重用SqlCommand参数?

转载 作者:行者123 更新时间:2023-12-02 04:31:20 25 4
gpt4 key购买 nike

我想为我的数据库实现一个简单的删除按钮。事件方法看起来像这样:

private void btnDeleteUser_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure?", "delete users",MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
{
command = new SqlCommand();
try
{
User.connection.Open();
command.Connection = User.connection;
command.CommandText = "DELETE FROM tbl_Users WHERE userID = @id";
int flag;
foreach (DataGridViewRow row in dgvUsers.SelectedRows)
{
int selectedIndex = row.Index;
int rowUserID = int.Parse(dgvUsers[0,selectedIndex].Value.ToString());

command.Parameters.AddWithValue("@id", rowUserID);
flag = command.ExecuteNonQuery();
if (flag == 1) { MessageBox.Show("Success!"); }

dgvUsers.Rows.Remove(row);
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (ConnectionState.Open.Equals(User.connection.State))
User.connection.Close();
}
}
else
{
return;
}
}

但我收到此消息:

A variable @id has been declared. Variable names must be unique within a query batch or stored procedure.

有什么办法可以重用这个变量吗?

最佳答案

Parameters.AddWithValue 将新参数添加到命令中。由于您在具有相同名称的循环中执行此操作,因此您会收到异常“变量名称必须是唯一的”。

因此,您只需要一个参数,将其添加到循环之前,并在循环中仅更改其值。

command.CommandText = "DELETE FROM tbl_Users WHERE userID = @id";
command.Parameters.Add("@id", SqlDbType.Int);
int flag;
foreach (DataGridViewRow row in dgvUsers.SelectedRows)
{
int selectedIndex = row.Index;
int rowUserID = int.Parse(dgvUsers[0,selectedIndex].Value.ToString());
command.Parameters["@id"].Value = rowUserID;
// ...
}

另一种方法是使用command.Parameters.Clear();第一的。然后,您还可以在循环中添加参数,而无需两次创建相同的参数。

关于c# - 如何在每次迭代中重用SqlCommand参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12100157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com