views:

479

answers:

2

Hello,

I know this may be something stupid but I decided to ask any way.

I've been trying to query something like:

 cursor.execute("select col1, col2   \
                    from my_tablem \
                    where afield like '%%s%'
                    and secondfield = %s
                    order by 1 desc " % (var1, var2) )

But I get an error in the like sentence. It doesn't like the extra % which I need to get all the results that contains the first %s value.

Ideas?

TIA!

+4  A: 

First, why aren't you using the Django ORM for this?

MyClass.objects.filter( aField__contains=var1, secondField__exact=var2 )

Second, be sure you're getting the SQL you expect.

stmt= "select... afield like '%%%s%%' and secondfield = '%s'..." % ( var1, var2 )
print stmt
cursor.execute( stmt )

Third, your method has a security hole called a SQL Injection Attack. You really should not be doing SQL like this.

If you absolutely must do things outside Django's ORM, you have to use bind variables in your query, not string substitution. See http://docs.djangoproject.com/en/dev/topics/db/sql/#performing-raw-sql-queries.

S.Lott
A: 

can just hack string '%' into search string?

var1 = '%' + var1 + '%'

then query normally:

cursor.execute("select col1, col2 from my_tablem where afield like %s and secondfield = %s order by 1 desc " , [var1, var2] )