Avoiding SQL Injection in SQL query with Like Operator using parameters?
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.
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.