如何使用更新ADO网 [英] How to use UPDATE in ado net

查看:115
本文介绍了如何使用更新ADO网的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行一个表(作业)的更新。但它不只是更换用新的一个旧值;在列中已经​​存在的价值我要补充(SUM)的新值(列的类型为int)。 这是我做的这么远,但我坚持:

I need to perform an update in a table(Homework). But it is not just replacing an old value with a new one; to the already existing value in the column i have to add(SUM) the new value(the column is of type int). This is what i did so far but i am stuck:

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();
        }
    }

我应该怎么增加这一翻译的 ??? 实现我的目标是什么?

What should i add intead of ??? to achieve my goal?

是否有可能做这种方式?我想避免使用许多查询。

Is it possible to do it this way? I want to avoid using to many queries.

推荐答案

如果我理解正确的话(我不知道我这样做),你希望是这样的:

If i understand you correctly (i'm not sure i do) you want something like this:

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

请注意我用的参数,而不是字符串连接,非常重要!

Notice how i've used parameters and not string concatenation, very important!!

这篇关于如何使用更新ADO网的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆