Python Equivalent Of Mysql_real_escape_string, For Getting Strings Safely Into Mysql?
Solution 1:
If you are using mysql-python, just try
MySQLdb.escape_string(SQL)
Example
>>>import MySQLdb>>>MySQLdb.escape_string("'")
"\\'"
Solution 2:
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.
Solution 3:
Is there a Python equivalent of PHP's mysql_real_escape_string?
Yes, it's escape_string
on the database connection object.
Notescape_string
on the MySQLdb
module, which is equivalent to mysql_escape_string
in PHP, and has the same potential vulnerability with multibyte character sets. You shouldn't use MySQLdb.escape_string
.
In any case, you are much better off using parameterised queries as in Alex's answer. This makes it easier to port to other databases (it's part of the DB-API standard, which escape_string
is not), and it's generally more convenient. (And much more convenient than parameterisation is in PHP.)
Solution 4:
In this particular case you just need to use executemany method of the cursor.
mysql_string = "INSERT INTO candidate (name, address) VALUES (%s,%s);"
cursor.executemany(mysql_string, v_dict.iteritems())
Solution 5:
beside MySQLdb.escape_string(SQL)
, pymysql python library also provide escape_string()
function.
>>>import pymysql>>>pymysql.escape_string("'")
"\\'"
>>>
Post a Comment for "Python Equivalent Of Mysql_real_escape_string, For Getting Strings Safely Into Mysql?"