Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do parameterized queries help against SQL injection?

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 txtTagNumber as a query parameter

    SqlCommand cmd = new SqlCommand("INSERT INTO dbo.Cars " +"VALUES(@TagNbr);" , conn); cmd.Parameters.Add("@TagNbr", SqlDbType.Int); cmd.Parameters["@TagNbr"].Value = txtTagNumber.Text; 
  2. Converting txtTagNumber to an integer before constructing the query

    int tagnumber = txtTagNumber.Text.ToInt16(); /* EDITED */ INSERT into Cars values(tagnumber.Text); /* then is it the same? */ 

Also, here I would use Regular Expression validation to stop insertion of illegal characters.

like image 272
sqlchild Avatar asked Mar 29 '11 05:03

sqlchild


People also ask

How parameterized queries help reducing the SQL injections?

Parametrized queries This method makes it possible for the database to recognize the code and distinguish it from input data. The user input is automatically quoted and the supplied input will not cause the change of the intent, so this coding style helps mitigate an SQL injection attack.

Are parameterized queries safe from SQL injection?

Correct usage of parameterized queries provides very strong, but not impenetrable, protection against SQL injection attacks.

How can SQL injection be prevented?

How to Prevent an SQL Injection. The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements. The application code should never use the input directly.


1 Answers

Parameterized queries do proper substitution of arguments prior to running the SQL query. It completely removes the possibility of "dirty" input changing the meaning of your query. That is, if the input contains SQL, it can't become part of what is executed because the SQL is never injected into the resulting statement.

like image 128
OJ. Avatar answered Sep 20 '22 08:09

OJ.