Wednesday, July 16, 2008

Escaping sql in python

Learned how to escape an sql statement when using the MySQLdb module in python today. Accoding to the docs which can be found at: http://mysql-python.sourceforge.net/MySQLdb.html the execute method will actually escape the input for you if it is necessary. For example:


connect.execute("insert into student (name,address) values (%s,%s)",(name,address,))

Will actually escape the name and address variable first before running it. So a few things to note:
1. There is no need to put quotation marks around the variable inside the query (ie. %s)
2. It is not a normal python substitute string as there is no % after the string but a , which means it is already the second variable to the function execute
3. The variables have to be a tuple and so we add a comma at the end of the list of variables to force it to become a tuple

All in all quite interesting...

0 comments: