How do parameterized queries help against SQL injection?

后端 未结 6 1418
有刺的猬
有刺的猬 2020-11-21 22:32

In both queries 1 and 2, the text from the textbox is inserted into the database. What\'s the significance of the parameterized query here?

  1. Passing tx

6条回答
  •  不知归路
    2020-11-21 23:14

    It is quite understandable why one would feel so.

    sqlQuery = "select * from users where username='+username+';"
    

    vs

    sqlQuery = "select * from users where username=@username;"
    

    Both the above queries seem to do the same thing.But they actually don't.

    The former uses input to for a query, the latter decides on the query but only substitutes the inputs as it is during the execution of the query.

    To be more clear, the parameters' values are located some where on the stack where the variables' memory is stored and is used for search when needed.

    So if we were to give ' OR '1'='1 as the input in username, the former would dynamically construct a new queries or queries as part of the sql query string sqlQuery which is then executed.

    While on the same input, latter would search for ' OR '1'=' in the username field of the users table with the statically specified query in the query string sqlQuery

    Just to consolidate it, this is how you use parameters to make query:

    SqlCommand command = new SqlCommand(sqlQuery,yourSqlConnection);
    
    SqlParameter parameter = new SqlParameter();
    parameter.ParameterName = "@username";
    parameter.Value = "xyz";
    
    command.Parameters.Add(parameter);
    

提交回复
热议问题