2017-10-17 144 views
1

我试图找到它。但我找不到我的答案。所以我决定提出这个问题。我需要你的帮助。C#SqlCommand查询更新

我希望将值添加到表值中,而不会覆盖Debit,Score列。它会增加当前值。

cmd = new SqlCommand("UPDATE Users SET [email protected], 
             [email protected] 
           WHERE [email protected]", 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(); 

例如:

Table, Phone: 999 | Debit: 1500 | Score: 100 //current <br> 

当我从textBox1的= 999,TextBox2中= 500,textBox3 = 50

Table, Phone: 999, Debit: 2000, Score: 150 //updating like that 

添加值我知道这样的SQL查询。但我不知道如何编写代码SqlCommand

UPDATE Users 
SET Debit = Debit + [user input], Score = Score + [user input] 
WHERE = Phone 

有什么建议吗?

(对不起,我的英语太可怕了,我希望你们明白我想问)

感谢

+0

你的SqlCommand似乎罚款,这是什么问题? – styx

回答

6

如果你想添加,只是添加

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

请注意逐字字符串@"..."语法。请不要忘记处置(明确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("Амжилттай"); 
    } 
} 
+0

它解决了我的问题。谢谢!我真的很感激。 :) –

1

这将帮助你....只是试图以这种方式..

SqlCommand cmd = new SqlCommand("UPDATE Users SET Debit = Debit + " + textBox2.Text + ", Score = Score + " + textBox3.Text + " WHERE Phone = " + textBox1.Text + "", con); 
       con.Open(); 
       cmd.ExecuteNonQuery(); 
       MessageBox.Show("Амжилттай"); 
       con.Close(); 

OR

SqlCommand cmd = new SqlCommand("UPDATE Users SET Debit = Debit + @debit, Score = 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(); 
+0

请不要* hardcode * sql,但使用*参数*(如在问题中) –

+0

但输出将是相同的德米特里Bychenko。 –

+0

是的,输出将是相同的,但是:(几乎)所有的查询都会不同(所以优化器应该为每个查询生成计划)。 2.查询很容易** sql注入**:想象一下'textBox2.Text'包含,比如说123; --'。在这种情况下,您将会查询:'“更新用户SET借方=借方+ 123 - ...”(请注意**注释**'--')。所以输入'123; --'将更新*整个表*,不只是所需的手机 –