C#-变量名称'@开始日期';已声明.变量名称在查询批处理或存储过程中必须是唯一的

本文关键字:变量名 过程中 存储过程 存储 唯一 批处理 日期 开始 #39@ C#- 声明 | 更新日期: 2023-09-27 17:59:26

我需要一种方法来更新数据网格视图中的单元格,并使用查询将其保存到数据库中,但我遇到了这个异常:

变量名称"@startdate"已声明。变量名称必须是唯一的查询批次或存储过程

这是我的代码:

private void toolStripLabel1_Click(object sender, EventArgs e)
{
    try
    {
        conn.Open();
        string query2 = "UPDATE [Semester] SET [Start_Date]=@startdate, " +
                        " [End_Date]=@enddate WHERE [Sem_Num]=@sem";
        cmd = new SqlCommand(query2, conn);
        if (dataGridView1.Rows.Count > 0)
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                cmd.Parameters.AddWithValue("@startdate", 
                                       dataGridView1.Rows[i].Cells[1].Value.ToString());
                cmd.Parameters.AddWithValue("@enddate", 
                                       dataGridView1.Rows[i].Cells[2].Value.ToString());
                cmd.Parameters.AddWithValue("@sem", 
                                  Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value));
                this.dataGridView1.EndEdit();
                cmd.ExecuteNonQuery();
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        conn.Close();
    }
}

C#-变量名称'@开始日期';已声明.变量名称在查询批处理或存储过程中必须是唯一的

清除每次迭代中的参数:

for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    cmd.Parameters.Clear();
    cmd.Parameters.AddWithValue("@startdate", dataGridView1.Rows[i].Cells[1].Value.ToString());
    cmd.Parameters.AddWithValue("@enddate", dataGridView1.Rows[i].Cells[2].Value.ToString());
    cmd.Parameters.AddWithValue("@sem", Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value));
    this.dataGridView1.EndEdit();
    cmd.ExecuteNonQuery();
}

或者定义循环外的参数并设置循环内的值:

var startParam = cmd.Parameters.Add("@startdate", SqlDbType.DateTime2);
var endParam = cmd.Parameters.Add("@enddate", SqlDbType.DateTime2);
var semParam = cmd.Parameters.Add("@sem", SqlDbType.Int);
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    startParam.Value = Convert.ToDateTime(dataGridView1.Rows[i].Cells[1].Value);
    endParam.Value = Convert.ToDateTime(dataGridView1.Rows[i].Cells[2].Value);
    semParam.Value = Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value);
    cmd.ExecuteNonQuery();
}

每次运行循环时,都会向同一命令添加新参数。

您需要清除参数或生成一个新命令。