使用Access 2010更新语句时出现语法错误

本文关键字:语法 错误 语句 Access 2010 更新 使用 | 更新日期: 2023-09-27 18:05:43

我一直得到一个错误,有一个语法错误在我的更新语句。对如何解决这个问题有什么想法吗?我在另一个程序中使用了非常相似的代码,它工作得很好,所以我被难住了。我已经尝试过在SQL语句中使用"answers",结果没有差异。

using (OleDbConnection con = new OleDbConnection(constring))
{
   try
   {
      string cmdstring = "UPDATE EMPLOYEE SET Location = '@location', Position = '@position' WHERE TellerNum = '@teller'";
      using (OleDbCommand cmd = new OleDbCommand(cmdstring, con))
      {
         cmd.Parameters.AddWithValue("@location", comboBox18.Text);
         cmd.Parameters.AddWithValue("@position", comboBox19.Text);
         cmd.Parameters.AddWithValue("@teller", comboBox17.Text);
         con.Open();
         cmd.ExecuteNonQuery();
         con.Close();
      }
      string inststring = "INSERT INTO EMPLOYEE (Comments) VALUES (@comments) WHERE TellerNum = @teller";
      using (OleDbCommand insert = new OleDbCommand(inststring, con))
      {
         insert.Parameters.AddWithValue("@comments", textBox8.Text);
         insert.Parameters.AddWithValue("@teller", comboBox17.Text);
         con.Open();
         insert.ExecuteNonQuery();
         con.Close();
      }
      MessageBox.Show("Submitted Successfully");
   }
   catch (Exception ex)
   {
      MessageBox.Show("Failed due to " + ex.Message);
   }
}

使用Access 2010更新语句时出现语法错误

正如注释中所解释的那样,语法错误是由于INSERT INTO语句中存在WHERE子句,但是如果您想用注释、位置和职位更新现有的员工记录,则只需一个命令即可完成。还要注意,不要将参数占位符放在单引号之间。如果这样做,将把占位符转换为隐藏参数值

的文字值。
using (OleDbConnection con = new OleDbConnection(constring))
{
   try
   {
      string cmdstring = @"UPDATE EMPLOYEE 
                           SET Location = @location, 
                           Comments = @Comments,
                           [Position] = @position 
                           WHERE TellerNum = @teller";
      using (OleDbCommand cmd = new OleDbCommand(cmdstring, con))
      {
         cmd.Parameters.AddWithValue("@location", comboBox18.Text);
         cmd.Parameters.AddWithValue("@comments", textBox8.Text);
         cmd.Parameters.AddWithValue("@position", comboBox19.Text);
         cmd.Parameters.AddWithValue("@teller", comboBox17.Text);
         con.Open();
         cmd.ExecuteNonQuery();
      }
   }
   catch (Exception ex)
   {
      MessageBox.Show("Failed due to " + ex.Message);
   }
}

如果你想在之前的注释后面添加一个新的注释,那么你的查询应该是(总是一个更新的查询)像这样

string cmdstring = @"UPDATE EMPLOYEE 
                     SET Location = @location, 
                     Comments = Comments + @Comments,
                     [Position] = @position 
                     WHERE TellerNum = @teller";

还有一个问题是使用保留关键字引起的。众所周知,使用保留关键字会导致语法错误。在您的情况下,POSITION是MS-Access中的保留关键字,因此,您需要将其括在方括号中。(但是,最好将该名称更改为其他名称,以避免将来重复相同的错误)