Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding SQL Injection in SQL query with Like Operator using parameters?

Taking over some code from my predecessor and I found a query that uses the Like operator:

SELECT * FROM suppliers
WHERE supplier_name like '%'+name+%';

Trying to avoid SQL Injection problem and parameterize this but I am not quite sure how this would be accomplished. Any suggestions ?

note, I need a solution for classic ADO.NET - I don't really have the go-ahead to switch this code over to something like LINQ.

like image 217
MikeJ Avatar asked Oct 23 '08 03:10

MikeJ


People also ask

Which methods can be used to avoid 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. The developer must sanitize all input, not only web form inputs such as login forms.

Do parameterized queries prevent SQL injection?

SQL Injection is best prevented through the use of parameterized queries.

What is best practice in defending against SQL injection?

Perform input validation Although prepared statements with query parameterization are the best defense against SQL injection, always create multiple defense layers. Like having limited privileges for a database user, input validation is a great practice to lower your application's risk in general.

What can I use instead of not like in SQL?

There's nothing wrong with LIKE and NOT LIKE . % and _ are wildcards. You asked to exclude rows that end with test and at least one character before that, any character.


2 Answers

try this:

var query = "select * from foo where name like @searchterm";
using (var command = new SqlCommand(query, connection))
{
  command.Parameters.AddWithValue("@searchterm", String.Format("%{0}%", searchTerm));
  var result = command.ExecuteReader();
}

the framework will automatically deal with the quoting issues.

like image 117
craigb Avatar answered Sep 23 '22 18:09

craigb


Simply parameterize your query:

SELECT * FROM suppliers WHERE supplier_name like '%' + @name + '%'

Now you can pass your "name" variable into the @name parameter and the query will execute without any danger of injection attacks. Even if you pass in something like "'' OR true --" it'll still work fine.

like image 26
Matt Hamilton Avatar answered Sep 19 '22 18:09

Matt Hamilton