5
Answers

Need help with update command for a MySQL database using C#

Ask a question
Peter

Peter

13y
3.4k
1
Hi,

I'm using Visual Studio to make a program in C# that needs to connect to a remote MySQL Database. I have everything working pretty well except the update command. This is the exact problem I am having: I can add a new row to a DataViewGrid and then add a value to one of the columns and then click my save/update button and have the MySQL server receive and save the added row and value. However if I add a row, then click save, then add the value to the row and then click save again I get the following error message: "Concurrency violation: the UpdateCommand affected 0 of the expected 1 records."

Here is the code I am using to connect to the database (my conn string will not be the actual one):

        private String connectionString = null;
        private MySqlConnection sqlConnection = null;
        private MySqlDataAdapter sqlDataAdapter = null;
        private MySqlCommandBuilder sqlCommandBuilder = null;
        private DataTable dataTable = null;
        private String selectQueryString = null;

            connectionString = ***My conn string***
            sqlConnection = new MySqlConnection(connectionString);

            try
            {
                sqlConnection.Open();
            }
            catch (Exception exceptionObj)
            {
                MessageBox.Show(exceptionObj.Message.ToString());
            }

            selectQueryString = "SELECT * FROM myTable";
            sqlDataAdapter = new MySqlDataAdapter(selectQueryString, sqlConnection);
            sqlCommandBuilder = new MySqlCommandBuilder(sqlDataAdapter);
            
            

            dataTable = new DataTable();
            sqlDataAdapter.Fill(dataTable);
            bindingSource1.DataSource = dataTable;

            databaseEditor_DataGridView.DataSource = bindingSource1;
            databaseEditor_DataGridView.Columns[0].Visible = false;



This is the code I use for the update:

            this.Validate();
            this.bindingSource1.EndEdit();

            try
            {
                sqlDataAdapter.Update(dataTable);
            }
            catch (Exception exceptionObj)
            {
                MessageBox.Show(exceptionObj.Message.ToString());
            }



Any and all help is appreciated.

Thanks,
Peter

Answers (5)