2

I'm starting to program a Python application that works with databases. Reading about prepared statements, I found how I'm supposed to write them:

...
strSQL = "select * from myTable where aField = $s" % (aValue)
cursor.execute(strSQL)
...

My question is: Isn't this vulnerable to SQL injection? If so, how can I prevent it?

Thank you

Barranka
  • 20,547
  • 13
  • 65
  • 83

2 Answers2

5

You are using the string formatting operator instead of bound SQL parameters, so your code is indeed at risk of SQL injection (once you fix the $s, which I take to be a typo).

The correct form is:

strSQL = "select * from myTable where aField = %s"
cursor.execute(strSQL, [aValue])
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 2
    The OP is not even using string formatting, as the 'template' used is `$s` instead of `%s`. – Martijn Pieters Apr 25 '13 at 18:37
  • Thank you for your answer. Indeed, I am screwing up by using `$s`. This are my first steps in Python, and I'm trying to correct my mistakes before they become serious. – Barranka Apr 25 '13 at 19:11
1

The way you have it, absolutely! Here's how you would "help" get around the sql injection

strSQL = "select * from myTable where aField = %s"
cursor.execute(strSQL, [aValue])

Pass the values as a list/tuple to the second argument on the cursor execute

Bryan
  • 6,682
  • 2
  • 17
  • 21