Adding Parameters to ADO.NET Commands
When constructing ADO.NET commands that modify data, it is crucial to utilize parameters to prevent SQL injection attacks and improve performance. Consider the following sample code:
SqlCommand command = new SqlCommand("INSERT INTO Product_table Values(@Product_Name,@Product_Price,@Product_Profit,@p)", connect);
This code attempts to insert values into a database table using parameters. However, it does not correctly define the parameters.
Solution:
The correct approach is to explicitly define each parameter with its name, data type, and value, as follows:
SqlCommand cmd = new SqlCommand("INSERT INTO Product_table (Product_Name, Product_Price, Product_Profit, p) " + "Values (@Product_Name, @Product_Price, @Product_Profit, @p)", connect); cmd.Parameters.Add("@Product_Name", SqlDbType.NVarChar, ProductNameSizeHere).Value = txtProductName.Text; cmd.Parameters.Add("@Product_Price", SqlDbType.Int).Value = txtProductPrice.Text; cmd.Parameters.Add("@Product_Profit", SqlDbType.Int).Value = txtProductProfit.Text; cmd.Parameters.Add("@p", SqlDbType.NVarChar, PSizeHere).Value = txtP.Text; cmd.ExecuteNonQuery();
Additional Considerations:
The above is the detailed content of How Can I Safely Add Parameters to ADO.NET Commands to Prevent SQL Injection?. For more information, please follow other related articles on the PHP Chinese website!