1

I am new to python, I come here from the land of PHP. I constructed a SQL query like this in python based on my PHP knowledge and I get warnings and errors

cursor_.execute("update posts set comment_count = comment_count + "+str(cursor_.rowcount)+" where ID = " + str(postid))
# rowcount here is int

What is the right way to form queries?

Also, how do I escape strings to form SQL safe ones? like if I want to escape -, ', " etc, I used to use addslashes. How do we do it in python?

Thanks

asked Oct 16, 2010 at 9:20

2 Answers 2

3

First of all, it's high time to learn to pass variables to the queries safely, using the method Matus expressed. Clearer,

tuple = (foovar, barvar)
cursor.execute("QUERY WHERE foo = ? AND bar = ?", tuple)

If you only need to pass one variable, you must still make it a tuple: insert comma at the end to tell Python to treat it as a one-tuple: tuple = (onevar,)

Your example would be of form:

cursor_.execute("update posts set comment_count = comment_count + ? where id = ?",
 (cursor_.rowcount, postid))

You can also use named parameters like this:

cursor_.execute("update posts set comment_count = comment_count + :count where id = :id",
 {"count": cursor_.rowcount, "id": postid})

This time the parameters aren't a tuple, but a dictionary that is formed in pairs of "key": value.

answered Oct 16, 2010 at 9:45
Sign up to request clarification or add additional context in comments.

3 Comments

Can I use something like this? cursor.execute("update posts set comment_count = %s where postid = %d",cursor_.rowcount,postid)
@arbithero: y-yes, I think you can. From wiki.python.org/moin/DbApiFaq I interpret that as a safe method as well. Where did you get that example from? I can't find %d anywhere.
@arbithero: added some examples about named queries if that looks better.
2

from python manual:

t = (symbol,)
c.execute( 'select * from stocks where symbol=?', t )

this way you prevent SQL injection ( suppose this is the SQL safe you refer to ) and also have formatting solved

eumiro
214k36 gold badges307 silver badges264 bronze badges
answered Oct 16, 2010 at 9:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.