1

Please let me know will following codes 100% prevent SQL injection in python

Sample1

username = request.GET('username')  # non-filtered user input
connection.execute("SELECT id,name,email FROM user WHERE username=%s LIMIT 1", (username,))

Sample2

username = request.POST('username')  # non-filtered user input
name = request.POST('name')  # non-filtered user input
email = request.POST('email')  # non-filtered user input
connection.execute("UPDATE user SET name=%s, email= %s WHERE username=%s LIMIT 1", (name, email, username,))

1 Answer 1

3

The concept of the %s is to isolate the data from the query. When you pass two arguments, they are combined in the module. It is intended to mitigate injection, but I'd be hesitant to say "100%"

Edit: many wiser than myself (maybe even real life security experts!) have weighed in here: https://security.stackexchange.com/questions/15214/are-prepared-statements-100-safe-against-sql-injection

Sign up to request clarification or add additional context in comments.

5 Comments

Even if I wouldn't say "100%", I'd say that for anyone asking this question, the database library is likely to do a better job of it than you are, so it's almost certainly the right answer. Which is why dbapi-2.0 and every database library that implements it all suggest using parameters, with a link to xkcd.
Agreed. Don't take it at face value for a banking website, but do this and find a bigger hole to plug.
This is the right way of doing it. Why would you hesitate to say 100%?
@DavidWallace, I don't know which SQL module is being used, and haven't read the source code to see what exactly it is doing. But feel free to say 100% if you'd like :)
@mhlester I am using MySQLdb (pypi.python.org/pypi/MySQL-python) driver. What i need to do for maximum secure sql query. I think the code i used 'is a kind' of prepared statements in python.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.