在Access数据库中插入新行

时间:2014-01-15 10:22:33

标签: c# ms-access datatable oledb oledbdataadapter

我在另一个Form中创建了以下代码:

窗体2

private DataTable dataTable;

internal void ReadTable(ref DataTable dt)
{
   dataTable = dt;
}

private void button1_Click(object sender, EventArgs e)
{
   DataRow dataRow = dataTable.NewRow();
   foreach (ListViewItem item in listView1.Items)
   {
      dataRow[item.SubItems[1].Text] = item.SubItems[item.SubItems.Count - 1].Text;
   }
   dataTable.Rows.Add(dataRow);
}

Form1中

private void button1_Click(object sender, EventArgs e)
{
   using (Form2 form = new Form2())
   {
      form.ReadTable(ref dataTable);
      form.ShowDialog();

      using (OleDbConnection oledbConnection = new OleDbConnection(connection))
      {
         oledbConnection.Open();
         string query = "SELECT * FROM Student";
         using (OleDbCommand oledbCommand = new OleDbCommand(query, oledbConnection))
         {
            using (OleDbDataAdapter oledbDataAdapter = new OleDbDataAdapter(oledbCommand))
            {
               using (OleDbCommandBuilder oledbCommandBuilder = new OleDbCommandBuilder(oledbDataAdapter))
               {
                  oledbDataAdapter.DeleteCommand = oledbCommandBuilder.GetDeleteCommand(true);
                  oledbDataAdapter.InsertCommand = oledbCommandBuilder.GetInsertCommand(true);
                  oledbDataAdapter.UpdateCommand = oledbCommandBuilder.GetUpdateCommand(true);
                  oledbDataAdapter.Update(dataTable);
                }
             }
          }
          oledbConnection.Close();
       }
   }
}

为什么在INSERT INTO语句中给出了语法错误?

1 个答案:

答案 0 :(得分:2)

解决方案如下:

...
using (OleDbCommandBuilder oledbCommandBuilder = new OleDbCommandBuilder(oledbDataAdapter))
{
   oledbCommandBuilder.QuotePrefix = "[";
   oledbCommandBuilder.QuoteSuffix = "]";
   oledbDataAdapter.DeleteCommand = oledbCommandBuilder.GetDeleteCommand(true);
   oledbDataAdapter.InsertCommand = oledbCommandBuilder.GetInsertCommand(true);
   oledbDataAdapter.UpdateCommand = oledbCommandBuilder.GetUpdateCommand(true);
   oledbDataAdapter.Update(dataTable);
}
...
相关问题