Вопрос

The Python docs state that

# 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()

I understand that the first option is vulnerable to an SQL injection attack. What I don't understand is why the second option would be more secure. Aren't these identical?

Это было полезно?

Решение

No - the execute method will take care to escape the argument correctly. Thus, if t is Robert'); DROP TABLE Students;--, the full command that would be transmitted to the DB engine in the second case would be something like

SELECT * FROM stocks WHERE symbol='Robert\'); DROP TABLE Students;--'

which is secure (note the backslash).

EDIT: (Actually, do note the comment by CL)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top