How do prepared statements help us prevent SQL injection attacks?
Wikipedia says:
Prepared statements are resilient against SQL injection, because
In SQL Server, using a prepared statement is definitely injection-proof because the input parameters don't form the query. It means that the executed query is not a dynamic query. Example of an SQL injection vulnerable statement.
string sqlquery = "select * from table where username='" + inputusername +"' and password='" + pass + "'";
Now if the value in the inoutusername variable is something like a' or 1=1 --, this query now becomes:
select * from table where username='a' or 1=1 -- and password=asda
And the rest is commented after --
, so it never gets executed and bypassed as using the prepared statement example as below.
Sqlcommand command = new sqlcommand("select * from table where username = @userinput and password=@pass");
command.Parameters.Add(new SqlParameter("@userinput", 100));
command.Parameters.Add(new SqlParameter("@pass", 100));
command.prepare();
So in effect you cannot send another parameter in, thus avoiding SQL injection...