Using sqlite3 for python, one method secure, one not, why?

Started by
1 comment, last by Matias Goldberg 11 years ago

# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)

# Do this instead
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print c.fetchone()

Taken from http://docs.python.org/2/library/sqlite3.html

My understanding is a SQL injection is when instead of supplying data or a variable you substitute a SQL command. My question is why is the second option better then the first. What makes the second option better then the first?

Advertisement
I guess the second version performs SQL escaping for you.

The 2nd option already knows the input is a parameter and there's no doubt it can't be part of the command in the statement, so SQL injection is not possible.

In the 1st option, you would have to properly escape the string, and there's the risk that you're not escaping it properly.

This topic is closed to new replies.

Advertisement