Update using MySqlDataAdapter doesn't work

usp picture usp · Mar 6, 2013 · Viewed 11.5k times · Source

I am trying to use MySqlDatAdapter to update a MySql table. But, the table never updates!!! I did this before but with SQL server. Is there anything else that is specific to MySql that I am missing in my code?

        DataTable myTable = new DataTable("testtable");

        MySqlConnection mySqlCon = new MySqlConnection(ConfigurationManager.ConnectionStrings["DBConStr"].ConnectionString);

        MySqlCommand mySqlCmd = new MySqlCommand("SELECT * FROM testtable WHERE Name = 'Tom'");
        mySqlCmd.Connection = mySqlCon;

        MySqlDataAdapter adapter = new MySqlDataAdapter(mySqlCmd);
        MySqlCommandBuilder myCB = new MySqlCommandBuilder(adapter);
        adapter.UpdateCommand = myCB.GetUpdateCommand();

        mySqlCon.Open();

        adapter.Fill(myTable);
        myTable.Rows[0]["Name"] = "Was Tom";
        myTable.AcceptChanges();
        adapter.Update(myTable);
        mySqlCon.Close();

Thanks

Answer

Tim Schmelter picture Tim Schmelter · Mar 6, 2013

Remove myTable.AcceptChanges() before the update. Othwerwise that will set all rows RowState to Unchanged, hence the DataAdapter will not know that something was changed.

adapter.Update(myTable) will call AcceptChanges itself after the update is finished.

So...

myTable.Rows[0]["Name"] = "Was Tom";
//myTable.AcceptChanges();
adapter.Update(myTable);