C# SQL更新查询返回错误

C# SQL更新查询返回错误,c#,sql,sql-server,ms-access,C#,Sql,Sql Server,Ms Access,更新查询返回“出现问题”消息。显示变量Productstock的消息框返回正确的值。anbody能否解释如何解决此问题?在+“WHERE ID=“+ 另外,请确保在cmd1上调用ExecuteNonQuery OleDbCommand cmd = new OleDbCommand("SELECT Stock FROM Products WHERE ID=" + ProductID + ";", conn); //run the database query OleDbDataReader cus

更新查询返回“出现问题”消息。显示变量Productstock的消息框返回正确的值。anbody能否解释如何解决此问题?

+“WHERE ID=“+

另外,请确保在
cmd1
上调用
ExecuteNonQuery

OleDbCommand cmd = new OleDbCommand("SELECT Stock FROM Products WHERE ID=" + ProductID + ";", conn); //run the database query
OleDbDataReader cusReader = cmd.ExecuteReader(); //read the result of the query
cusReader.Read();           
ProductStock = (int)cusReader.GetValue(0);
cusReader.Close();
MessageBox.Show((ProductStock).ToString()); // checks that the form is being accessed and the SELECT query works

OleDbCommand cmd1 = new OleDbCommand("UPDATE Products SET Stock=" + (ProductStock - 1) + "WHERE ID= " + ProductID +";", conn);

try
{
   if (cusReader.RecordsAffected > 0)
   {
      MessageBox.Show("no issue was experienced");
   }
   else
   {
      MessageBox.Show("An issue occured when decreasing stock");
   }
   cusReader.Close();
}
catch (Exception ex)
{
   MessageBox.Show("An error occured in query.\n" + ex.Message);
}
请使用以上命令


问题:股票价值和位置之间没有空格

请尝试此操作。它应该可以工作

OleDbCommand cmd1 = new OleDbCommand("UPDATE Products SET Stock=" + (ProductStock - 1) + " WHERE ID= " + ProductID +";", conn);
尝试一次更新(不要将
select
update
分开:某人可以在您执行
select
之后但在您开始
update
之前修改数据),然后检查受影响的行。使sql具有可读性以避免明显错误

OleDbCommand cmd1 = new OleDbCommand("UPDATE Products SET Stock=" + (ProductStock - 1) + " WHERE ID= " + ProductID, conn);

您是否正在执行update语句?您可能需要在
cmd1
上调用
ExecuteNonQuery
。我想这就是@Dirk的意思。不起作用的代码是从一个运行良好的更新查询中逐字复制的,所以我假设have@peter.petrov是的,当然也要像你在回答中说的那样在查询中加一个空格。我不确定如何使用
ExecuteNonQuery
string sql = 
  // Parametrize your query or at least format it out: 
  $@"update Products
        set Stock = Stock - 1
      where Id = {ProductId} and
            Stock >= 1 -- added: you must have stock to decrease";

// Wrap IDisposable into using
using (OleDbCommand cmd = new OleDbCommand(sql, conn)) {
  int affected = cmd.ExecuteNonQuery();

  if (affected > 0) 
    MessageBox.Show("No issue was experienced");
  else
    MessageBox.Show("An issue occured when decreasing stock");
}