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?
This extension was deprecated in PHP 5.5. 0, and it was removed in PHP 7.0.
PHP provides mysql_real_escape_string() to escape special characters in a string before sending a query to MySQL. This function was adopted by many to escape single quotes in strings and by the same occasion prevent SQL injection attacks.
Definition and Usage The real_escape_string() / mysqli_real_escape_string() function escapes special characters in a string for use in an SQL query, taking into account the current character set of the connection. This function is used to create a legal SQL string that can be used in an SQL statement.
If you are using mysql-python, just try
MySQLdb.escape_string(SQL)
Example
>>> import MySQLdb
>>> MySQLdb.escape_string("'")
"\\'"
cursor.executemany('INSERT INTO candidate (name, address) VALUES (%s, %s)',
[(v_dict['name'], v_dict['address'])] * len(v_dict))
should do what your code appears to attempt -- inserting the same identical values N times (you're looping on v_dict.iteritems()
but completely ignoring the loop variables, and instad just reusing those specific two values from v_dict
each and every time). Of course if you mean something completely different the second line will need to be changed accordingly, but the key idea anyway is to use placeholders, not string formatting, for such tasks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With