【问题标题】:Update stock quantity in database from button click通过单击按钮更新数据库中的库存数量
【发布时间】:2014-04-11 00:46:08
【问题描述】:

当我点击 acceptBTN 时,我想更新 stockTBL 中某个项目的数量

private void acceptBTN_Click(object sender, EventArgs e)
    {

        string constring = @"Data Source=|DataDirectory|\LWADataBase.sdf";
        string Query = "UPDATE stockTBL SET Quantity = Quantity+ '" + this.quantityTxt.Text + "' where [Item Name] = '" + this.itemTxt.Text + "';";
        SqlCeConnection conDataBase = new SqlCeConnection(constring);
        SqlCeCommand cmdDataBase = new SqlCeCommand(Query, conDataBase);

        try
        {
            conDataBase.Open();
            MessageBox.Show("Sucess");






            //displays a system error message if a problem is found
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);

        }
    }  

这是我的代码,当我点击 acceptBTN 时,它只显示 MessageBox 而不更新数量。

【问题讨论】:

  • 发布后才发现!还是谢谢。

标签: c# sql database


【解决方案1】:

您甚至没有执行刚刚创建的查询。请先尝试执行它

conDataBase.Open();
cmdDataBase.ExecuteNonQuery();
conDataBase.Close();

一些建议:

  1. 尝试使用parameterized queries 代替字符串连接 以避免SQL Injection 攻击。
  2. 对于一次性物品,始终使用using statements,以确保它们被妥善处理。

    string constring = @"Data Source=|DataDirectory|\LWADataBase.sdf";
    string Query = "UPDATE stockTBL SET Quantity = Quantity + @quantity where [Item Name] = @name";
    using(SqlCeConnection conDataBase = new SqlCeConnection(constring))
    using(SqlCeCommand cmdDataBase = new SqlCeCommand(Query, conDataBase))
    {
        cmdDataBase.Parameters.AddWithValue("@quantity", int.Parse(quantityTxt.Text));
        cmdDataBase.Parameters.AddWithValue("@name", itemTxt.Text);
        conDataBase.Open();
        cmdDataBase.ExecuteNonQuery();
        cmdDataBase.Close();
    }
    

【讨论】:

  • 它没有更新,只是拖掉了现有数据:之前说的(例如):5,现在说 56。而不是 11,假设订购的数量是 6。
  • @GrantWinney 是的,请参阅SqlCeParameterCollectionmethods:msdn.microsoft.com/en-us/library/…
  • 其实和普通的SqlCommand没有什么不同,因为它们都继承自同一个基类:)
  • 编辑中包含的代码完美运行,感谢@Selman22
  • @user3521452 您的欢迎说明它不起作用,因为您将 quantityTxt.Text 用单引号括起来,因此查询正在执行 string concatenation 而不是 addition.
【解决方案2】:

你可能想要cmdDataBase.ExecuteNonQuery。您打开了连接,但从未执行过查询。

MSDN Referece.

【讨论】:

    猜你喜欢
    • 2014-01-17
    • 2016-06-11
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多