我在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 - 数字
答案 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);
}
}
希望它能帮助别人。 :)