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.
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.
SQL Injection is best prevented through the use of parameterized queries.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With