Search code examples
c#databasems-accessdatatableoledb

C# DataTable update Access Database


How can I save a DataTable to a file. accdb (Access) existing one? I've used the following code and it does not work:

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

The variable dataTable is initialized with the original contents of the file, then it was modified by adding a row and now I have to update the table in the database.

I tried using the following code, but that does not work :(

OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM Student", connection);
OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder(da);
da.InsertCommand = cmdBuilder.GetInsertCommand(true);
// create and insert row in the DataTable
da.Update(dataTable);

Solution

  • Assuming that you have made some changes in the datatable, then you could pass the generated update/insert/delete command to the adapter in this way

    oledbDataAdapter.DeleteCommand = oledbCommandBuilder.GetDeleteCommand();
    oledbDataAdapter.InsertCommand = oledbCommandBuilder.GetInsertCommand();
    oledbDataAdapter.UpdateCommand = oledbCommandBuilder.GetUpdateCommand();
    oledbDataAdapter.Update(datatable);
    

    Now the adapter knows how to update your table