C# 我得到一个错误;将数据类型nvarchar转换为real时出错。”;
我的代码如下,你能告诉我问题可能在哪里,这样我们就可以按仓库ID降价7%吗C# 我得到一个错误;将数据类型nvarchar转换为real时出错。”;,c#,mysql,sql,sql-update,C#,Mysql,Sql,Sql Update,我的代码如下,你能告诉我问题可能在哪里,这样我们就可以按仓库ID降价7%吗 private void button4_Click(object sender, EventArgs e) { try { myConnection = new SqlConnection(frm.cs); myCommand = new SqlCommand("update I
private void button4_Click(object sender, EventArgs e)
{
try
{
myConnection = new SqlConnection(frm.cs);
myCommand = new SqlCommand("update Inventory set Price=@Price where WarehouseCode=6", myConnection);
myConnection.Open();
myCommand.Parameters.AddWithValue("@Price", "@Price * 0.7");
myCommand.ExecuteNonQuery();
myConnection.Close();
MessageBox.Show("Update successfully!");
DisplayData();
if (myConnection.State == ConnectionState.Open)
{
myConnection.Dispose();
}
}
我不认为你真的想要一个参数。如果您想将价格降低7%,那么您应该直接在查询中进行计算。您还需要修正算法:
update Inventory set Price = Price * 0.93 where WarehouseCode = 6
或者,您可能希望将折扣作为参数传递。如果是:
update Inventory set Price = Price * (1 - @Discount) where WarehouseCode=6", myConnection
您可以将值
0.07
作为一个值传递给参数@Discount
,因为在C#code中您没有为@Price
分配任何值,而您的仓库Id
和折扣率
由最终用户分配,我建议您的代码如下:
private void button4_Click(object sender, EventArgs e)
{
try
{
var discountRate = 0.07; //could be Convert.ToDouble(textBox1.Text) or something else
var warehouseId = 6; //again, could be Convert.ToInt32(textBox2.Text) or something else
myConnection = new SqlConnection(frm.cs);
myCommand = new SqlCommand("update Inventory set Price=Price*(1-@DiscountRate) " +
"where WarehouseCode=@WarehouseId", myConnection);
myConnection.Open();
myCommand.Parameters.AddWithValue("@DiscountRate", discountRate);
myCommand.Parameters.AddWithValue("@WarehouseId", warehouseId);
myCommand.ExecuteNonQuery();
myConnection.Close();
MessageBox.Show("Update successfully!");
DisplayData();
if (myConnection.State == ConnectionState.Open)
{
myConnection.Dispose();
}
}
catch
{
}
}
我也建议你重新考虑一下你的查询,因为它将更新所有的产品价格相同的值,你可以考虑传递参数<代码> @产品ID < /> >,你的查询为
update Inventory set Price=Price*(1-@DiscountRate)
where WarehouseCode=@WarehouseId and ProductCode=@ProductId
当然,这是一个例子。@vivaldi在做这样的更新时要非常小心。如果你最初的尝试成功了,你会降价30%,而不是7%。如果仓库是2个,有两个不同的ID,例如6和1,会怎么样?换句话说,这两个仓库中所有产品的价格都必须改变。上述方法对其中一个仓库非常有效,但即使在为WarhouseID1=3添加了第二个声明之后,第二个仓库也不起作用;在这里,您可以考虑在(61,1)< /代码> <代码>仓库ID。因此,您的参数是一个ID字符串,我不建议这样做,因为这将需要对这个字符串进行解析,您可以调用查询两次或尽可能多地用不同的IDSI调用。然而,当我们试图通过将负改为正来恢复7%的差异时,它没有起作用:myCommand=newsqlcommand(“更新库存集价格=价格+价格*@discentrate”+”,其中仓库代码位于(1,3)”,myConnection);myConnection.Open();这背后有什么原因吗?