如何在 ado net 中使用 UPDATE

How to use UPDATE in ado net(如何在 ado net 中使用 UPDATE)
本文介绍了如何在 ado net 中使用 UPDATE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在表格中执行更新(作业).但这不仅仅是用新值替换旧值;对于列中已经存在的值,我必须添加(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 net 中使用 UPDATE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)