I'm trying to work with an Access database through OleDb. I need to:
- get data from the database to dataset
- change the data in the dataset
- update this dataset back to the database.
First two task are done. But I'm unable to update changed dataset back to the database. I do not see any error, no exception. Data in dataset are correctly changed (fruits.WriteXml writes correct result), but data inside the database are not changed.
Why are the data not changed in the database?
Thank you.
To reproduce it: (database file: https://drive.google.com/open?id=0ByImDaWMXaHAUGRIbTNLT0dHU0k&authuser=0)
private void button1_Click(object sender, EventArgs e)
{
updateDb();
}
private void updateDb()
{
String connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\\local_workspaces\\visualstudio10\\FruitShop\\Database2.accdb;User Id=;Password=;";
DataSet fruits = new DataSet();
OleDbConnection connection = new OleDbConnection(connectionString);
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM fruits", connection);
adapter.Fill(fruits);
MessageBox.Show("Current value: " +fruits.Tables[0].Rows[0]["quantity"].ToString());
//setting new value
fruits.Tables[0].Rows[0]["quantity"] = 1111;
fruits.AcceptChanges();
OleDbCommandBuilder commandBuilder = new OleDbCommandBuilder(adapter);
adapter.UpdateCommand = commandBuilder.GetUpdateCommand();
adapter.Update(fruits);
MessageBox.Show("New value: " + fruits.Tables[0].Rows[0]["quantity"].ToString());
connection.Close();
}
edit:
the code is adapted from this example: http://msdn.microsoft.com/en-us/library/at8a576f(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2 The original example doesn't work as well for me.
Can it be because of Access database? (I'm unable to try other databases right now)
solution:
Thank you for your help. To get it working, it is needed to get changes in the dataset and update only these changes otherwise it is not working (for me).
DataSet changes = fruits.GetChanges();
if (changes != null)
{
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.UpdateCommand = builder.GetUpdateCommand();
adapter.Update(changes);
fruits.AcceptChanges();
}