rounen rounen - 1 year ago 63
MySQL Question

Can't minus in sql

string sql2 = "UPDATE project_table SET resources=(resources-" + txtresource.Text + ") where code=" + project_code + "";

I used the query below to update my table, but it seem my database didn't minus the resources. What did I do wrong?

Answer Source

Convert it and then use in query like

int val = Convert.ToInt32(txtresource.Text.Trim());
SET resources = resources - val

Finally consider using SQLParameter for avoiding SQL Injection Attack

string sql2 = "UPDATE project_table SET resources = resources - @val where code = @code";
//Create Command
SqlCommand cmd = new SqlCommand(sql2, connectionObject);
cmd.CommandType = CommandType.Text;

cmd.Parameters.Add(SQLDbType.INT, @val).Value = val;
cmd.Parameters.Add(SQLDbType.VARCHAR, @code).Value = project_code;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download