[英]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.