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!
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.
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.
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 .
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.
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] )
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