Reputation: 7119
cursor.execute("SELECT word_id from words where word_name = '%s'" %
(word))
if cursor.fetchone() == None:
return False
return True
I was thinking that including the explicit '
on close of the %s
format parameter might prevent this, but
"'best'; DELETE * FROM words;"
would be a really nasty string to search for! I know Django
always suggests handling your parameter-based queries through their tamper-proof SQL cleanser, but if I am using it for a offline app, how might I be able to access those methods and avoid this situation in the first place? Does anybody do it this way?
Upvotes: 0
Views: 146
Reputation: 4047
If you are not doing this from a django application then you don't need to rely on django's API to protect you from SQL injection attacks. The db API you are working in will provide its own methods for safely inputing parameters into SQL queries. For example if you are using SQLite your can reference the documentation at http://docs.python.org/library/sqlite3.html for how to safely construct a parameterized SQL statement:
# Never do this -- insecure!
symbol = 'IBM'
c.execute("... where symbol = '%s'" % symbol)
# Do this instead
t = (symbol,)
c.execute('select * from stocks where symbol=?', t)
Upvotes: 4
Reputation: 6294
Are you not able to use the raw()
Manager to perform your query? This would still use Django's SQL sanitizing functions but allow you to run raw SQL queries against your model.
In this case I'm assuming the model is named 'Word', so
Word.objects.raw("SELECT word_id from words where word_name = %s", [word])
should work just fine. Note that you're using word as a parameter and not a direct string, which is what protects you. The documentation for raw()
is located here
Upvotes: 1