更新c#中的语法错误

本文关键字:语法 错误 更新 | 更新日期: 2023-09-27 17:55:01

我想用datagridview数据更新数据库,这是我的代码:

        for (int i = 0; i < dataGridView1.Rows.Count; i++)
        {
            SqlCommand cmd2 = new SqlCommand("UPDATE Pharmacy_Items Set Quantity= Quantity + " + dataGridView1.Rows[x].Cells[4].Value + " where ItemName='" + dataGridView1.Rows[x].Cells[1].Value + "'", mycon);
            cmd2.ExecuteNonQuery();
            x += 1;
        }

更新c#中的语法错误

两件事不对:

  1. tdataGridView1.Rows [x] .Cells[4]。Value可能会产生一个带有逗号的值,而这个值会被数据库识别因此值10,4不会被视为10.4但4会被视为新字段

    你从dataGridView中分配的某个值是空的

  2. 使用参数而不是像这样构建查询,不仅更安全,而且还可以解决数量字段

  3. 的问题

示例:

cmd2.CommandText = "UPDATE Pharmacy_Items Set Quantity = Quantity + @Quantity where ItemName = @ItemName";
cmd2.Parameters.AddWithValue(@Quantity, dataGridView1.Rows[x].Cells[4].Value);  
cmd2.Parameters.AddWithValue(@ItemName, dataGridView1.Rows[x].Cells[1].Value);
cmd2.ExecuteNonQuery();

编辑:OP想要增加quantity字段。

cmd2.CommandText = "UPDATE Pharmacy_Items Set Quantity = Quantity + @Quantity where ItemName = @ItemName";
cmd2.Parameters.AddWithValue(@Quantity, dataGridView1.Rows[x].Cells[4].Value);  
cmd2.Parameters.AddWithValue(@ItemName, dataGridView1.Rows[x].Cells[1].Value);
cmd2.ExecuteNonQuery();

如果单元格可以为空,您可以像这样将空替换为0,这样您只需将0添加到quantity中,而不会得到异常。

cmd2.CommandText = "UPDATE Pharmacy_Items Set Quantity = Quantity + @Quantity where ItemName = @ItemName";
cmd2.Parameters.AddWithValue(@Quantity, dataGridView1.Rows[x].Cells[4].Value ?? 0);  
cmd2.Parameters.AddWithValue(@ItemName, dataGridView1.Rows[x].Cells[1].Value);
cmd2.ExecuteNonQuery();

您应该使用参数,在SQL查询中附加字符串是一个非常糟糕的主意(SQL注入)。下面应该会使错误更清楚:

for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    decimal qty = Convert.ToDecimal(dataGridView1.Rows[x].Cells[4].Value);
    string itemName = dataGridView1.Rows[x].Cells[1].Value;
    string commandText = "UPDATE Pharmacy_Items Set Quantity= Quantity + @p1 WHERE ItemName = @p2";
    SqlCommand cmd2 = new SqlCommand(commandText, mycon);
    cmd2.Parameters.AddWithValue("@p1", qty);
    cmd2.Parameters.AddWithValue("@p2", itemName);
    cmd2.ExecuteNonQuery();
}

我将假设语法错误来自SQL连接。如果是这样,参数化应该可以解决这个问题。您可以使用像Dapper这样的工具使正确参数化变得很简单:

for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    string itemName = (string)dataGridView1.Rows[x].Cells[1].Value;
    // note: I don't know what the actual type is here; int? decimal?
    int quantity = (int)dataGridView1.Rows[x].Cells[4].Value;
    myCon.Execute(
        "UPDATE Pharmacy_Items Set Quantity=Quantity+@quantity where ItemName=@itemName",
        new { itemName, quantity });
    x += 1;
}