简体   繁体   中英

Escaping single and double quotes for mysql in python

I am using mysql.connector python library with python 2.7

I have a unicode string which may or may not contain single and double quotes. Here are the things I tried for my escape function:

def escape(string):
#string.MySQL.escape_string()
#string = string.decode('string_escape')
#string = string.encode('unicode-escape').replace("'", "''")
#string = string.encode('unicode-escape').replace('"', '\"')
#string = string.encode('unicode-escape').replace("'", u"\u2019")
#string = string.encode('unicode-escape').replace('''"''', u"\u201D")
#string = string.encode('unicode-escape').replace('''''', u"\u201D")
return string

Nothing seems to have worked. I tried using this function but still gives mysql syntax error.

I need something within mysql.connector library which escapes the single and double quotes without breaking the unicode as well as mysql query.

Here is an example of SQL query I am using:

"""SELECT * FROM messages WHERE msg_id = '{msg_id}'""".format(**db_dict)

Let me know if any more details needed

EDIT : Example SQL query updated

cursor.execute('SELECT * FROM messages WHERE msg_id = %s', (db_dict['msg_id'],)) is what you want to run here. Standard string escapes aren't supported by python's database interface, and, per @bobince's comment, are a security hole to boot.

MySQLdb officially declares to use the format paramstyle, but it also supports the pyformat style*, so if you want to use parameters from a dict, you can use:

db_dict = {'msg_id': "1'2'3", ...}
cursor.execute("SELECT * FROM messages WHERE msg_id = %(msg_id)s", db_dict)

Using string manipulation to create sql queries only leads to sql injection vulnerabilities, so you should never do it.


*... most db connectors that use python string formatting behind the screen do the same, they specify one of format or pyformat as paramstyle but actually support both. The dbapi2 doesnt't allow to specify two values here, but it doesn't forbid to support multiple parmstyles either. If you write code that potentially uses an unknowon dbapi2 connector it's enough that you can query a supported paramstyle, being able to know all would be nice but it's not necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM