-3

my function is

void counter()
        {
            int sum = 0;
            for (int i = 0; i < dataGridView2.Rows.Count; i++)
            {
                sum += Convert.ToInt32(dataGridView2.Rows[i].Cells[1].Value);

            }

            int sum1 = 0;
            for (int j = 0; j < dataGridView3.Rows.Count; j++)
            {

                sum1 += Convert.ToInt32(dataGridView3.Rows[j].Cells[1].Value);
            }

            int total = sum - sum1;


            string Coonstring = "datasource=localhost;port=3306;username=root;password=***;Charset=utf8";
            string cmd = "update project.material set number =total where name= '" + this.txt.Text + "';";
            MySqlConnection connectionDatabase = new MySqlConnection(Coonstring);
            MySqlCommand cmddata = new MySqlCommand(cmd, connectionDatabase);
            MySqlDataReader myreader;

I need to update the number column with the value of ( Total). So what is the right way to do that's.

Regards

tariq
  • 43
  • 7
  • Change the literal "total" to use the value in the variable, either using string concatenation or a String.Format. Is that what you are asking for? – BradleyDotNET Apr 24 '14 at 19:28

2 Answers2

1

You want to use ExecuteNonQuery() to run your update statement. The proper way to load the new value of number is to use a parameter:

string cmd = "update project.material set number = @total where name= @name;";
MySqlConnection connectionDatabase = new MySqlConnection(Coonstring);
MySqlCommand cmddata = new MySqlCommand(cmd, connectionDatabase);
cmddata.Parameters.Add("@name", this.txt.Text);
cmddata.Parameters.Add("@total", total);
cmddata.ExecuteNonQuery();

You can simply concatenate the string instead, but it's not that much harder to use parameters - and it's flat out better.

Community
  • 1
  • 1
Jon B
  • 51,025
  • 31
  • 133
  • 161
0

following command should work this out:

string cmd = string.Format("update project.material set number = {0} where name= '{1}'",
                           total,
                           this.txt.Text);

also you may want to consider parameters usage for commands

Andrew
  • 3,648
  • 1
  • 15
  • 29