2016-01-23 48 views
1

一旦產品被買了它應該從庫存數量如何從股票C#SQL扣除數量

double qun; 

qun = Convert.ToDouble(dataGridView1.Rows[0].Cells[3].Value) - Convert.ToDouble(textBox2.Text); 

sqlconnection = new SqlCeConnection(ConnectionString); 
sqlcommand = new SqlCeCommand(); 
sqlconnection.Open(); 
sqlcommand.Connection = sqlconnection; 
sqlcommand.CommandText = (@"UPDATE ItemStock_Info SET Quantity [email protected] WHERE [Item_Number]='"+ textBox1.Text +"'"); 
sqlcommand.Parameters.Add("@qun", qun); 

sqlcommand.ExecuteNonQuery(); 
sqlconnection.Close(); 
+1

[SQL注入警報](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - 您應該**不**將您的SQL語句連接在一起 - 使用**參數化查詢**,而不是避免SQL注入 –

回答

1

減少如果變量qun是你應該從值在數據庫表中減去它不是那麼銷售數量只需將該值重新覆蓋您的庫存值

@"UPDATE ItemStock_Info 
    SET Quantity = Quantity - @qun 
    WHERE ... " 

給你的一條消息。爲什麼使用數量參數而不是where條件?這應該避免不惜一切代價和參數應該以不同的方式添加

sqlcommand.CommandText = (@"UPDATE ItemStock_Info 
          SET Quantity = Quantity - @qun 
          WHERE [Item_Number][email protected]"; 
sqlcommand.Parameters.Add("@qun", SqlDbType.Float).Value = qun; 
sqlCommand.Parameters.Add("@num", SqlDbType.NVarChar).Value = textBox1.Text; 
sqlcommand.ExecuteNonQuery(); 

我應該在這裏添加警告。如果將您的數量值更改爲零以下的水平,我想您不希望減去所售數量。由於這是一個SQL Server CE數據庫,假設沒有人可以更改背後的值,並且在減除操作之前已經測試了此條件,但在多用戶環境中,我建議您使用具有更好地支持這些領域的併發。

+1

謝謝,它工作:) –