[英]C# - “Syntax error in update statement” when trying to update the access database using datagridview (also using OleDbCommandBuilder)
我在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);
}
}
當我單擊更新按鈕時,出現消息框錯誤,提示“更新語句中的語法錯誤”
字段1:ID-自動編號,主鍵字段2:TRIP COST-編號
伙計們,我自己找到了答案。
發生錯誤是因為字段名稱包含一個空格,即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);
}
}
希望它能幫助別人。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.