【问题标题】:Update the First Row in a database C# mysql更新数据库 C# mysql 中的第一行
【发布时间】:2016-09-09 08:15:54
【问题描述】:

我的问题是:

  1. 我想从数据库中选择一行,数据应该在过期时排列(那些还没有过期的,我不想限制它)。超过当前日期的项目必须单独放置。并且使用所有相同的 ITEMID 让我们说 I00001。

  2. 然后选择我要更新数据库的第一行后。如果数量达到0则进入下一行更新,以此类推。

这是我的例子

  • 这是当前数据库screenshot
  • 我要选择 itemid where = I00001 并减去 50。
  • 那么它应该看起来像this
  • 那我想按照上面说的到期时间来安排。
  • 选择第一行。
  • 从数量中减去 50。 (正如我在上面提到的)。

这是我的代码:

for (int i = 0; i < dataGridView.Rows.Count; i++)
{
    cmd = new MySqlCommand(@"SELECT * FROM inventory2 WHERE itemid = @itemid ORDER BY expiry ", sqlconnection);

    cmd = new MySqlCommand(@"UPDATE inventory2 SET quantity = @quantity WHERE itemid = @itemid ORDER BY expiry)", sqlconnection);

    sqlconnection.Open();
    cmd.ExecuteNonQuery();
    sqlconnection.Close();
}

我愿意接受其他建议。我希望你能理解我的问题。非常感谢。很抱歉,我无法发送另一个屏幕截图。

【问题讨论】:

  • 我会通过没有 c# 代码的 sql 来完成这一切。但现在是凌晨 4 点,我下班了。明天去看看
  • 哦,没关系,谢谢。

标签: c# mysql winforms


【解决方案1】:

试试这个,

void UpdateQuantity() {
        // your connection string
        MySqlDataAdapter adp = new MySqlDataAdapter("Select * from table where ItemID = " + 13 + " Order BY expiry", cnn); // I have test db and I used it
        DataTable dt = new DataTable();
        adp.Fill(dt);
        int deductNum = 50;
        foreach (DataRow item in dt.Rows)
        {
            int value = (int)item["quantity"];
            if (value >= deductNum) // if had enough stock we don't need to pass the next line
            {
                int result = value - deductNum;
                item["quantity"] = result.ToString();
                break; // so need to exit from loop
            }
            else
            {
                deductNum -= value; // else we deduct value count from deduction
                item["quantity"] = 0; // quantity finished so it will be 0
            }
        }
        MySqlCommandBuilder cmb = new MySqlCommandBuilder(adp);
        adp.UpdateCommand = cmb.GetUpdateCommand();
        adp.Update(dt);
        dataGridView1.DataSource = dt; //to show the result
    }

(你可以计算:))

希望有帮助,

【讨论】:

  • 谢谢。我欠你一个
  • 嗨!我有机会尝试您的代码,但它显示错误。 “附加信息:指定的演员表无效。”在 int 值 = Convert.ToInt32((int)item["quantity"]);。谢谢:)
  • 我的答案中没有转换。 Cast 和 Comvert 一起会给出这个错误。 @菲利普
猜你喜欢
  • 2014-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多