Python equivalent of mysql_real_escape_string, for getting strings safely into MySQL?

Posted by AP257 on Stack Overflow See other posts from Stack Overflow or by AP257
Published on 2010-04-01T14:41:10Z Indexed on 2010/04/01 14:43 UTC
Read the original article Hit count: 462

Filed under:
|

Hi all

Is there a Python equivalent of PHP's mysql_real_escape_string?

I'm trying to insert some strings into a MySQL db direct from Python, and keep getting tripped up by quotes in the strings.

mysql_string = "INSERT INTO candidate (name, address) VALUES  " 
for k, v in v_dict.iteritems():
    mysql_string += " ('" + v_dict['name'] + "', '" + v_dict['address'] + "'), "
mysql_string += ";"
cursor.execute(mysql_string)

I've tried re.escape() but that escapes every non-alphanumeric character in the strings, which isn't what I need - I just need to escape single quotes in this instance (plus more generally anything else that might trip up MySQL).

Could do this manually I guess, but is there a smarter way to do it in Python?

© Stack Overflow or respective owner

Related posts about python

Related posts about mysql