Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "like" in a cursor/query with a parameter in python (django)

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!

like image 784
Juan129 Avatar asked Mar 13 '09 18:03

Juan129


People also ask

What is %s in Python SQL?

We need to supply values in placeholders ( %s ) before executing a query. Pass Python variables at the placeholder's position when we execute a query. We need to pass the following two arguments to a cursor. execute() function to run a parameterized query.

How do you use variables in Python query?

In order to do reference of a variable in query, you need to use @ . Instead of filter value we are referring the column which we want to use for subetting or filtering. {0} takes a value of variable myvar1.

How do you bind variables to SQL query in sqlite3 in Python?

Call sqlite3. Cursor. execute(query, parameters) on the previous result with an SQL query named query and with ? characters as wildcards for variable values and parameters as a tuple containing the variables to be used in query to execute a parameterized SQL query in sqlite3 .


2 Answers

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.

like image 128
S.Lott Avatar answered Sep 22 '22 01:09

S.Lott


can 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] )
like image 38
brobas Avatar answered Sep 20 '22 01:09

brobas