python避免SQL注入的方法:
python中的pymysql在執行sql前,會對sql中的特殊字符進行轉義,如:
def escape_string(value, mapping=None):
"""escape_string escapes *value* but not surround it with quotes.
Value should be bytes or unicode.
"""
if isinstance(value, unicode):
return _escape_unicode(value)
assert isinstance(value, (bytes, bytearray))
value = value.replace('\\', '\\\\')
value = value.replace('\0', '\\0')
value = value.replace('\n', '\\n')
value = value.replace('\r', '\\r')
value = value.replace('\032', '\\Z')
value = value.replace("'", "\\'")
value = value.replace('"', '\\"')
return value
執行sql的正確方法,不要在sql中拼接參數,字符轉義只會針對參數args,例如:
# query作為sql模板,args為將要傳入的參數
execute(query, args=None)