Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

mysql

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?

like image 439
AP257 Avatar asked Apr 01 '10 14:04

AP257


People also ask

Is mysql_real_escape_string deprecated?

This extension was deprecated in PHP 5.5. 0, and it was removed in PHP 7.0.

Does mysql_real_escape_string prevent SQL injection?

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.

What is mysqli_ real_ escape_ string for?

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.


2 Answers

If you are using mysql-python, just try

MySQLdb.escape_string(SQL)

Example

>>> import MySQLdb
>>> MySQLdb.escape_string("'")
"\\'"
like image 50
YOU Avatar answered Oct 14 '22 19:10

YOU


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.

like image 15
Alex Martelli Avatar answered Oct 14 '22 20:10

Alex Martelli