简体   繁体   English

如果数据库中已经存在一个项目,如何更新它的数量

[英]How to update a quantity of an item if it already exists in database

I have a productstbl table consisting of Name , Quantity and other attributes.我有一个productstbl表,其中包含NameQuantity和其他属性。

When I want to buy a new item that is already present in productstbl table I need to update the Quantity .当我想购买productstbl表中已经存在的新商品时,我需要更新Quantity

SqlCommand cmdCount = new SqlCommand("SELECT COUNT(*) FROM Productstbl WHERE Name = @name", con);
con.Open();

cmdCount.Parameters.AddWithValue("@name", NameBox.Text);

int count = (int)cmdCount.ExecuteScalar();

con.Close();

if (count > 0)
{
    SqlCommand cmd = new SqlCommand("SELECT Qunatity FROM Productstbl WHERE Name = @name, Quantity = @quantity", con);
    con.Open();

    cmd.Parameters.AddWithValue("@name", NameBox.Text);

    int ExistingQTY = (int)cmdCount.ExecuteScalar();     // I get error here 
}

cmd = new SqlCommand("INSERT INTO Historytbl (Name, Date, Price, Quantity, Total_Price, Sup_Name, Process, Retail_Price) VALUES (@name, @date, @price, @quantity, @total_price, @sup_name, @process, @retail_price)", con);
con.Open();

cmd.Parameters.AddWithValue("@name", NameBox.Text);
cmd.Parameters.AddWithValue("@date", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("@price", PriceBox.Text);
cmd.Parameters.AddWithValue("@quantity", ExistingQTY);
cmd.Parameters.AddWithValue("@total_price", TotalPriceBox.Text);
cmd.Parameters.AddWithValue("@sup_name", comboBox1.Text);
cmd.Parameters.AddWithValue("@process", "buy");
cmd.Parameters.AddWithValue("@retail_price", RetailPriceBox.Text);

cmd.ExecuteNonQuery();
con.Close();

MessageBox.Show("Record inserted successfully");
DisplayData();
ClearData();

If you want to update a quantity of a product, it is best for to get the quantity in the database if it already exists the database.如果要更新一个产品的数量,如果数据库已经存在,最好从数据库中获取数量。

I make a code example, you can have a look.我做了一个代码示例,你可以看看。

private void Form1_Load(object sender, EventArgs e)
{
    comboBox1.Items.Add("Juice");
    comboBox1.Items.Add("Apple");
    comboBox1.Items.Add("Milk");
    ShowData();

}
public void ShowData()
{
    string connstr = "connstr";
    SqlConnection connection = new SqlConnection(connstr);
    connection.Open();
    string cmd = "select * from Product";
    DataSet set = new DataSet();
    SqlDataAdapter adapter = new SqlDataAdapter(cmd, connection);
    adapter.Fill(set);
    dataGridView1.DataSource = set.Tables[0];
}
private void button1_Click(object sender, EventArgs e)
{
    string connstr = "connstr";
    SqlConnection connection = new SqlConnection(connstr);
    connection.Open();
    SqlCommand cmdCount = new SqlCommand("SELECT COUNT(*) FROM Product WHERE Name = @Name", connection);
    cmdCount.Parameters.AddWithValue("@Name", comboBox1.SelectedItem.ToString());
    int count = (int)cmdCount.ExecuteScalar();
    int i = 0;
    if(count>0)
    {
        SqlCommand command = new SqlCommand("SELECT Quantity FROM Product WHERE Name = @Name",connection);
        command.Parameters.AddWithValue("@Name", comboBox1.SelectedItem.ToString());
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                i = Convert.ToInt32(reader["Quantity"]);

            }
        }
        SqlCommand updatecmd = new SqlCommand("Update Product set Quantity=@Quantity, Date=@Date where Name=@Name",connection);
        updatecmd.Parameters.AddWithValue("@Quantity", i + numericUpDown1.Value);
        updatecmd.Parameters.AddWithValue("@Date", DateTime.Now);
        updatecmd.Parameters.AddWithValue("@Name", comboBox1.SelectedItem.ToString());
        updatecmd.ExecuteNonQuery();
        dataGridView1.DataSource = null;
        ShowData();
        MessageBox.Show("Update successfully");
    }
    else
    {
        SqlCommand insertcmd = new SqlCommand("insert into Product(Name,Quantity,Date,Price)values(@Name,@Quantity,@Date,@Price)",connection);
        insertcmd.Parameters.AddWithValue("Name", comboBox1.SelectedItem.ToString());
        insertcmd.Parameters.AddWithValue("@Quantity",numericUpDown1.Value);
        insertcmd.Parameters.AddWithValue("@Date",DateTime.Now);
        insertcmd.Parameters.AddWithValue("Price",Convert.ToInt32(textBox1.Text));
        insertcmd.ExecuteNonQuery();
        dataGridView1.DataSource = null;
        ShowData();
        MessageBox.Show("Insert successfully");
    }
    connection.Close();
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if(comboBox1.SelectedItem.ToString()== "Juice")
    {
        textBox1.Text = "10";
    }
    if (comboBox1.SelectedItem.ToString() == "Apple")
    {
        textBox1.Text = "5";
    }
    if (comboBox1.SelectedItem.ToString() == "Milk")
    {
        textBox1.Text = "8";
    }
}

Tested Result:测试结果:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 仅当MongoDB数据库中的条目已存在时才更新 - Update an entry in a MongoDB database only if it already exists 如何使用实体框架更新数据库中的数量 - How to update quantity in database using Entity Framework 检查数据库中是否已存在列表项的最佳方法是什么? - What is the best way to check if an item of a list already exists in database? 如果记录已经存在,如何更新记录 EF - How to update record if record already exists EF DbMigrator.Update导致数据库'名称'已存在 - DbMigrator.Update resulting in a Database 'name' already exists EF Core:更新数据库错误:关系“所有者”已经存在 - EF Core: update database error: relation "Owner" already exists 如果项目已存在,则 C# 更新多元素列表项目,否则将其添加为新项目 - C# update multiple element list item if item already exists otherwise add it as new item 具有相同密钥的项目已存在 - item with same key already exists 用户购买产品时如何更新最新数量? 数据库没有减少数量 - How to update latest quantity when user buy a product? The database have not reduced the quantity EF Core Postgres Update-Database 正在尝试创建已经存在的数据库 - EF Core Postgres Update-Database is trying to Create Database which already exists
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM