2011-04-24 79 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