How can prepared statements protect from SQL injection attacks?

前端 未结 9 2035
予麋鹿
予麋鹿 2020-11-21 05:40

How do prepared statements help us prevent SQL injection attacks?

Wikipedia says:

Prepared statements are resilient against SQL injection, because

9条回答
  •  温柔的废话
    2020-11-21 06:08

    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...

提交回复
热议问题