iboss
iboss

Reputation: 41

Code runs but doesn't update database

This code is supposed to save some values in textboxes to a specific row. The code runs just fine with no hiccups, but refuses to actually update the database no matter what I do.

try
{
    using (var con = new OleDbConnection())
    {
        con.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\User\Desktop\esoft\gym\gym\bin\Debug\Clients.accdb;";
        con.Open();

        using (var com = new OleDbCommand())
        {
             com.Connection = con;
             com.CommandText = "UPDATE gym SET BMI = @bmi and Health = @health and weight_change_to_healthy_bmi = @weight WHERE ID = @id";

             com.Parameters.AddWithValue("@bmi", bmi.Text);
             com.Parameters.AddWithValue("@health", health.Text);
             com.Parameters.AddWithValue("@weight", change.Text);
             com.Parameters.AddWithValue("@id", id.Text);

             com.ExecuteNonQuery();
         }
     }

     MessageBox.Show("Saved");
 }
 catch (Exception ex)
 {
     MessageBox.Show("Not saved: " + ex.Message);
 }

Any help would be much appreciated.

Upvotes: 0

Views: 79

Answers (1)

Soner Gönül
Soner Gönül

Reputation: 98868

As Alex mentioned, SET part needs , instead of AND for multiple columns.

Check UPDATE syntax1;

UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;

But I wanna say a few things more;

  • Don't use AddWithValue as much as you can. It may generate unexpected and surprising results sometimes. Use Add method overload to specify your parameter type and it's size.
  • Open your connection just before you execute your command. That means, you should open your connection just before your ExecuteNonQuery line.
  • Based on it's name, ID column should be some numeric value instead of character. Consider to change it's type or consider to change it's column name that refers some character typed column name.

1: I know I know.. a w3school link

Upvotes: 5

Related Questions