Click here to Skip to main content
15,881,715 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
private void btnConfirm_Click(object sender, EventArgs e)
        {
            string product_id = txtProductID.Text;
            string product_name = txtProductName.Text;
            string product_price = txtPrice.Text;
            string product_type = txtType.Text;
            string product_qty = txtQty.Text;
            string order_qty = txtOrderQty.Text;


            //2. create a sql insertion string
            string sql = "update productinfo set product_id = 'p1',product_name = 'p2',product_price = 'p3',product_type='p4',product_qty= (product_qty - order_qty),'p5'";
            sql += " where product_id ='" + product_id + "'";
            sql = sql.Replace("p1", product_id);
            sql = sql.Replace("p2", product_name);
            sql = sql.Replace("p3", product_price);
            sql = sql.Replace("p4", product_type);
            sql = sql.Replace("p5", product_qty);
            MessageBox.Show(sql);

            m1.ExecuteNonQuery(sql);
            MessageBox.Show("done");
            refreshProductList();
        }

where txtOrderqty.Text is the amount to be reduced in product_qty

What I have tried:

I tried
product_qty= (product_qty - order_qty),'p5'";
but it's not working
Posted
Updated 13-Sep-21 1:31am

1 solution

Not like that!

Your code is vulnerable to SQL Injection[^]. NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.

Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]

C#
const string sql = "update productinfo set product_name = @name, product_price = @price, product_type = @type, product_qty = product_qty - @order_qty where product_id = @id";

using (var connection = new SqlConnection("..."))
using (var command = new SqlCommand(sql, connection))
{
    command.Parameters.AddWithValue("@name", product_name);
    command.Parameters.AddWithValue("@price", product_price);
    command.Parameters.AddWithValue("@type", product_type);
    command.Parameters.AddWithValue("@order_qty", order_qty);
    command.Parameters.AddWithValue("@id", product_id);
    
    connection.Open();
    command.ExecuteNonQuery();
}
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900