Sonu_Orai
Sonu_Orai

Reputation: 397

How to update a column of sql table adding a variable to the current value in C#

Im using this code

updt = new SqlCommand("update dailysale set totalunit1 = totalunit1 - " + double.Parse(textBox3.Text) +" where material = '" + comboBox4.SelectedItem.ToString() +"' AND sn > '" + enmbr + "' ", agr, transac);

but this doesn't make update whereas

SqlCommand up2 = new SqlCommand("update dailysale set sn = sn +2 where sn > '" + enmbr + "' ", agr,transac);

is working for me

Upvotes: 1

Views: 51

Answers (2)

Steve
Steve

Reputation: 216323

Using a parameterized query avoid subtle syntax errors hidden in the string concatenation and prevent any possibility of Sql Injections

string cmdText = "update dailysale set totalunit1 = totalunit1 - @sold " + 
                 "where material = @mat AND sn > @emb";
updt = new SqlCommand(cmdText, agr);
updt.Transaction = transac;
updt.Parameters.AddWithValue("@sold", Convert.ToDouble(textbox1.Text));
updt.Parameters.AddWithValue("@mat", comboBox4.SelectedItem.ToString());
updt.Parameters.AddWithValue("@emb", embr);
int rowsUpdated = updt.ExecuteNonQuery();
if(rowsUpdated > 0)
   MessageBox.Show("Record updated!");

In your original text you miss the double quotes before the AND and probably the conversion of your textbox to a double introduces a decimal separator not understood by your database. Instead a parameterized query leaves the work to correctly quote the values to the framework code and your query text is no more obscured by the string concatenations and quoting

Upvotes: 3

Skye MacMaster
Skye MacMaster

Reputation: 914

Did you check the result count?

if updt.ExecuteNonQuery() <> 0 Then

If it's zero then your where clause didn't select any records

If it's not zero then maybe you didn't commit your transaction.

transact.Commit()

Upvotes: 0

Related Questions