2011-04-24 30 views
3

我需要在表中執行更新(作業)。但這不僅僅是用新的價值取代舊的價值;到列中已經存在的值,我必須添加(SUM)新值(列的類型爲int)。 這是我做過什麼,到目前爲止,但我堅持:如何在ado net中使用UPDATE

protected void subscribeButton_Click(object sender, EventArgs e) 
    { 
     string txtStudent = (selectedStudentLabel.Text.Split(' '))[0]; 
     int studentIndex = 0; 
     studentIndex = Convert.ToInt32(txtStudent.Trim());   

     SqlConnection conn = new SqlConnection("Server=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Trusted_Connection=True;User Instance=yes"); 
     conn.Open(); 
     string sql2 = "UPDATE student SET moneyspent = " + ?????? + " WHERE id=" + studentIndex + ";"; 
     SqlCommand myCommand2 = new SqlCommand(sql2, conn); 

     try 
     { 
      conn.Open(); 
      myCommand2.ExecuteNonQuery(); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine("Error: " + ex); 
     } 
     finally 
     { 
      conn.Close(); 
     } 
    } 

我應該加什麼這一翻譯的???達到我的目標?

可以這樣做嗎?我想避免使用許多查詢。

+1

請停止通過連接字符串來構建SQL命令!這是獲得一些討厭的SQL注入的最好方法:http://en.wikipedia.org/wiki/SQL_injection – 2011-04-24 18:14:33

+0

對不起,哥們,但這只是一項家庭作業,我很瞭解SQL注入的風險。不過謝謝你提醒。 – sfrj 2011-04-24 18:19:22

回答

12

如果我理解正確的話(我不知道我這樣做),你想是這樣的:

string sql2 = "UPDATE student SET moneyspent = moneyspent + @spent WHERE [email protected]"; 
SqlCommand myCommand2 = new SqlCommand(sql2, conn); 
myCommand2.Parameters.AddWithValue("@spent", 50) 
myCommand2.Parameters.AddWithValue("@id", 1) 

注意我是如何使用的參數,而不是字符串連接,非常重要!

+1

+1使用綁定參數並防止SQL注入。 – Codo 2011-04-24 18:04:15

+1

我知道我應該使用參數來避免SQL注入,但這只是一些作業。 我按照你所說的做了SET moneyspent = moneyspent + someIntValue',但我在數據庫中完全沒有看到任何變化。我錯過了什麼嗎? – sfrj 2011-04-24 18:14:34