why we use parametric SQL query instead of simple one.
C#
string CustomerName = "Anderson"
//Simple MSSQL Query
string qr = "SELECT CustomerCode FROM accounts WHERE CustomerName = '" + CustomerName + "' ";
// Parametric MSSQL Query
List param = new List().ToList();
sparam.Add(new SqlParameter() { ParameterName = "@AccountName", Value = CustomerName });
string qr = "SELECT CustomerCode FROM accounts WHERE CustomerName = @AccountName ";

Sachin SinghRank #66 · 26.2K reputationPosted Sep 23, 2021, 11:44 PM EDT
we use parameterized queries to prevent SQL injection attacks.
let's see from your example
suppose, I am a malicious user (hacker), so instead of entering Customer Name, this is what I will enter
// I Enter :- Sachin'+OR+1=1--
SELECT CustomerCode FROM accounts WHERE CustomerName = '" Sachin'+OR+1=1--
+ "' "
so, now you know what will happen, I will get all CustomerCode, so it will be a great loss to your company.
With parameterized query, the input goes as a parameter and doesn't concatenate with the query , and thus it prevents the SQL Injection Attack.
Satya KarkiRank #78 · 24.6K reputationPosted Sep 26, 2021, 1:32 AM EDT
Srinivasan RamamoorthiRank #877 · 2.5K reputationPosted Sep 23, 2021, 3:13 PM EDT
satheesh d190 reputationPosted Oct 30, 2021, 6:12 AM EDT
Using parametrized query helps prevent SQL Injection attacks. This can be done even by using stored procedures.
FOR EXAMPLE:
using (SqlConnection connection = new SqlConnection ("DBConnectionString"))
{
SqlConnection command = new SqlCommand("Select * from tblProduct where Product like '" + ProductText.Text + "%'", connection);
connection.Open();
ProductGridview.DataSource = command.ExecuteReader();
ProductGridview.DataBind();
}
If you search any item in the textbox, it will automatically filter and return the product. But there is a possible of entering bad query in the text box which will cause SQL injection. To prevent this use parametrized query or stored procedures
Rijwan AnsariRank #82 · 24.2K reputationPosted Oct 30, 2021, 9:03 AM EDT