C#SqlCommand查询更新

Tam*_*ius 1 c# sql-server sqlcommand

我试图找到它.但我找不到我的答案.所以我决定问这个问题.我需要你的帮助.

我希望在不覆盖Debit,Score列的情况下将值添加到表值中.它会增加当前价值.

cmd = new SqlCommand("UPDATE Users SET Debit=@debit, 
                                       Score=@score 
                                 WHERE Phone=@phone", con);

con.Open();

cmd.Parameters.AddWithValue("@phone", textBox1.Text);
cmd.Parameters.AddWithValue("@debit", textBox2.Text);
cmd.Parameters.AddWithValue("@score", textBox3.Text);

cmd.ExecuteNonQuery();

MessageBox.Show("?????????");
con.Close();
Run Code Online (Sandbox Code Playgroud)

例如:

Table, Phone: 999 | Debit: 1500 | Score: 100 //current <br>
Run Code Online (Sandbox Code Playgroud)

当我从textBox1 = 999,textBox2 = 500,textBox3 = 50添加值时

Table, Phone: 999, Debit: 2000, Score: 150 //updating like that 
Run Code Online (Sandbox Code Playgroud)

我知道这样的SQL查询.但我不知道如何编写代码SqlCommand

UPDATE Users 
SET Debit = Debit + [user input], Score = Score + [user input] 
WHERE = Phone
Run Code Online (Sandbox Code Playgroud)

有什么建议?

(抱歉我的英语很糟糕,我希望你们明白我要问的是什么)

谢谢

Dmi*_*nko 5

如果要添加,只需添加:

cmd = new SqlCommand(@"UPDATE Users 
                          SET Debit = Debit + @debit, 
                              Score = Score + @score 
                        WHERE Phone = @phone", con);
Run Code Online (Sandbox Code Playgroud)

请注意逐字字符串@"..."语法.请不要忘记处理(显式Close反模式):

string sql = 
  @"UPDATE Users 
       SET Debit = Debit + @debit, 
           Score = Score + @score 
     WHERE Phone = @phone";

//TODO: put the right connection string instead of "MyConnectionStringHere"
//DONE: IDisposable (SqlConnection) should be wrapped into using 
using (var con = new SqlConnection("MyConnectionStringHere")) {
  con.Open();

  //DONE: IDisposable (SqlCommand) should be wrapped into using
  using (var cmd = new SqlCommand(sql, con)) {
    //TODO: AddWithValue is often a bad choice; change to Add 
    cmd.Parameters.AddWithValue("@phone", textBox1.Text);
    cmd.Parameters.AddWithValue("@debit", textBox2.Text);
    cmd.Parameters.AddWithValue("@score", textBox3.Text);

    cmd.ExecuteNonQuery();
    //TODO: a better policy is to read localized strings from resources
    MessageBox.Show("?????????");
  }
}
Run Code Online (Sandbox Code Playgroud)