views:

2168

answers:

5

I am writing a searching function, and have thought up of this query using parameters to prevent, or at least limit, SQL injection attacks. However, when I run it through my program it does not return anything:

SELECT * FROM compliance_corner WHERE (body LIKE '%@query%') OR (title LIKE '%@query%')

Can parameters be used like this? or are they only valid in an instance such as:

SELECT * FROM compliance_corner WHERE body LIKE '%<string>%' (where <string> is the search object).

EDIT: I am constructing this function with VB.NET, does that have impact on the syntax you guys have contributed?

Also, I ran this statement in SQL Server: SELECT * FROM compliance_corner WHERE (body LIKE '%max%') OR (title LIKE %max%')` and that returns results.

A: 

You may have to concatenate the % signs with your parameter, e.g.:

LIKE '%' || @query || '%'

Edit: Actually, that may not make any sense at all. I think I may have misunderstood your problem.

Will Wagner
+4  A: 

Try:

select * from compliance_corner
   where (body like '%' + @query + '%') or (title like '%' + @query + '%')
tvanfosson
As Adam has pointed out in his answer, this does not protect against SQL injection. The query should be parameterized.
DOK
A: 

you have to do:

LIKE '%' + @param + '%'

Andrew Bullock
+7  A: 

Your visual basic code would look something like this:

Dim cmd as New SqlCommand("SELECT * FROM compliance_corner WHERE (body LIKE '%' + @query + '%') OR (title LIKE '%' + @query + '%')")

cmd.Parameters.Add("@query", searchString)
John
As Adam has pointed out in his answer, this does not protect against SQL injection. The query should be parameterized.
DOK
Could you provide an example where this does not prevent against SQL injection? From my testing it works fine
John
+5  A: 

Well, I'd go with:

 Dim cmd as New SqlCommand(
 "SELECT * FROM compliance_corner"_
  + " WHERE (body LIKE @query )"_ 
  + " OR (title LIKE @query)")

 cmd.Parameters.Add("@query", "%" +searchString +"%")
James Curran
This is correct, the accepted answer provided by John has the wrong syntax!
Adam
I am unsure how his syntax is incorrect, his solution worked just fine. I have a function that constructs and returns an SQL statement for use in a datatable or whatever else.
Anders
Additional Note:Syntax for C# using the MySQLDataAdapter =da = new MySQLDataAdapter("SELECT * FROM tableA WHERE fieldA = @fieldA");da.SelectCommand.Parameters.AddWithValue("@fieldA","%" + someValue + "%");
John M