tags:

views:

875

answers:

3

Ok so I'm not that experienced in Python.

I have the following Python code:

cursor.execute("INSERT INTO table VALUES var1, var2, var3,")

where var1 is an integer, var2 & var3 are strings.

How can I write the variable names without python including them as part of the query text?

+4  A: 
cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", var1, var2, var3)

The database API does proper escaping and quoting of variables. Be careful not to use the string formatting operator (%), because it does not do any escaping or quoting.

Ayman Hourieh
Interesting, why does it work with the vars separately instead of in an array (var1,var2,var3)?
Andomar
According to the DB API specs, it looks like it can be either way: http://www.python.org/dev/peps/pep-0249/
Ayman Hourieh
+3  A: 

http://www.amk.ca/python/writing/DB-API.html

Be careful when you simply append values of variables to your statements: Imagine a user naming himself ';DROP TABLE Users;' -- That's why you need to use sql escaping, which Python provides for you when you use the cursor.execute in a decent manner. Example in the url is:

cursor.execute("insert into Attendees values (?, ?, ?)", (name,
seminar, paid) )
Numlock
Actually, it is not SQL escaping. It's variable binding, which is far simpler and more direct. The values are bound into the SQL statement after parsing, making it immune to any injection attack.
S.Lott
+3  A: 

Different implementations of the Python DB-API are allowed to use different placeholders, so you'll need to find out which one you're using -- it could be (e.g. with MySQLdb):

cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))

or (e.g. with sqlite3 from the Python standard library):

cursor.execute("INSERT INTO table VALUES (?, ?, ?)", (var1, var2, var3))

or others yet (after VALUES you could have (:1, :2, :3) , or "named styles" (:fee, :fie, :fo) or (%(fee)s, %(fie)s, %(fo)s) where you pass a dict instead of a map as the second argument to execute). Check the paramstyle string constant in the DB API module you're using, and look for paramstyle at http://www.python.org/dev/peps/pep-0249/ to see what all the parameter-passing styles are!

Alex Martelli