C# - "Syntax error in update statement" 尝试使用 datagridview 更新访问数据库时(也使用 OleDbCommandBuilder)

C# - "Syntax error in update statement" when trying to update the access database using datagridview (also using OleDbCommandBuilder)

我在 datagridview 中显示一个数据,我正在尝试从 datagridview 更新数据库。所以我使用 OleDbCommandBuilder 来生成更新命令。单击更新按钮时我得到 "Syntax error in update statement"。

这是我的代码:

 private void listBox9_SelectedValueChanged(object sender, EventArgs e)
 {
        AppDomain.CurrentDomain.SetData("DataDirectory", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
        connection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|\Trip Sheet Management System\WABCO.mdb");
        sql = "SELECT ID,[TRIP COST] FROM TMSDETAILS";
        dataAdapter = new OleDbDataAdapter(sql, connection);
        dataTable = new DataTable();
        bindingSource = new BindingSource();
        connection.Open();
        dataAdapter.Fill(dataTable);
        bindingSource.DataSource = dataTable;
        dataGridView1.DataSource = bindingSource;
        connection.Close();
  }


 private void button8_Click(object sender, EventArgs e)
    {

        commandBuilder = new OleDbCommandBuilder(dataAdapter);

        try
        {
            dataAdapter.Update(dataTable);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

当我点击更新按钮时,我在 MessageBox 中收到错误提示 "Syntax error in update statement"

字段 1:ID - 自动编号,主键 字段 2:旅行费用 - 数字

伙计们,我自己找到了答案。

发生错误是因为字段名称包含 space 即 TRIP COST。

只需在命令生成器语句旁边添加两行。

commandBuilder.QuotePrefix = "[";

commandBuilder.QuoteSuffix = "]";

这是编辑后的代码。

 private void listBox9_SelectedValueChanged(object sender, EventArgs e)
{
    AppDomain.CurrentDomain.SetData("DataDirectory", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
    connection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|\Trip Sheet Management System\WABCO.mdb");
    sql = "SELECT ID,[TRIP COST] FROM TMSDETAILS";
    dataAdapter = new OleDbDataAdapter(sql, connection);
    dataTable = new DataTable();
    bindingSource = new BindingSource();
    connection.Open();
    dataAdapter.Fill(dataTable);
    bindingSource.DataSource = dataTable;
    dataGridView1.DataSource = bindingSource;
    connection.Close();
}


private void button8_Click(object sender, EventArgs e)
{

    commandBuilder = new OleDbCommandBuilder(dataAdapter);
    commandBuilder.QuotePrefix = "["; 
    commandBuilder.QuoteSuffix = "]";

    try
    {
        dataAdapter.Update(dataTable);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

希望对其他人有所帮助。 :)