Sign in to follow this  

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

Recommended Posts

# 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


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?

Edited by Biffenbob

Share this post

Link to post
Share on other sites

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.

Edited by Matias Goldberg

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this