C# - "更新语句中的语法错误"尝试使用datagridview更新访问数据库时(也使用OleDbCommandBuilder)

时间:2015-02-03 15:42:32

标签: c# winforms datagridview

我在datagridview中显示数据,我正在尝试从datagridview更新数据库。所以我使用OleDbCommandBuilder来生成更新命令。单击更新按钮时出现“更新语句中的语法错误”。

这是我的代码:

 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中收到错误,说“更新语句中的语法错误”

字段1:ID - 自动编号,主键 字段2:TRIP COST - 数字

1 个答案:

答案 0 :(得分:2)

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

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

只需在命令构建器语句旁边添加两行。

commandBuilder.QuotePrefix =" [&#34 ;;

commandBuilder.QuoteSuffix ="]&#34 ;;

这是编辑过的代码。

 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);
    }
}

希望它能帮助别人。 :)